C Bitwise Operators Example

given the following function:

int boof(int n) {
    return n + ~n + 1;
}

What does this function return? I'm having trouble understanding exactly what is being passed in to it. If I called boof(10), would it convert 10 to base 2, and then do the bitwise operations on the binary number?

This was a question I had on a quiz recently, and I think the answer is supposed to be 0, but I'm not sure how to prove it.

note: I know how each bitwise operator works, I'm more confused on how the input is processed.

Thanks!


Bitwise operations will not change the underlying representation of the number to base 2 - all math on the CPU is done using binary operations regardless.

What this function does is take n and then add it to the two's complement negative representation of itself. This essentially negates the input. Anything you put in will equal 0.

Let me explain with 8 bit numbers as this is easier to visualize.

10 is represented in binary as 00001010.

Negative numbers are stored in two's complement (NOTing the number and adding 1)

So the (~n + 1) portion for 10 looks like so:

11110101 + 1 = 11110110

So if we take n + ~n+1:

00001010 + 11110110 = 0

Notice if we add these numbers together we get a left carry which will set the overflow flag, resulting in a 0. (Adding a negative and positive number together never means the overflow indicates an exception!)

See this The CARRY and OVERFLOW flag in Binary Arithmetic


When n is an int, n + ~n will always result in an int` that has all bits set.

Strictly speaking, the behavior of adding 1 to such an int will depend on the representation of signed numbers on the platform. The C standard support 3 representations for signed int :

  • for Two's Complement machines (the vast majority of systems in use today), the result will be 0 since an int with all bits set is -1.

  • on a One's Complement machine (which are pretty rare today, I believe), the result will be 1 since an int with all bits set is 0 or -0 (negative zero) or undefined behavior.

  • a Signed-magnitude machine (are there really any of these still in use?), an int with all bits set is a negative number with the maximum magnitude (so the actual value will depend on the size of an int ). In this case adding 1 to it will result in a negative number (the exact value, again depends on the number of bits that are used to represent an int ).

  • Note that the above ignores that it might be possible for some implementations to trap with various bit configurations that might be possible with n + ~n .

    链接地址: http://www.djcxy.com/p/36380.html

    上一篇: 行宏:do / while(0)vs范围块

    下一篇: C位运算符示例