Computing the absolute value of a signed 32-bit two’s complement integer with bitwise operators

3.3k Views Asked by At

solution:

int iabs(int a) {
   int t = a >> 31;
   a = (a^t) - t;
   return a;
}

Can someone explain at the math level why shifting 31 bits to the right, xoring this result with t and subtracting t from this work?

1

There are 1 best solutions below

3
On BEST ANSWER

This is more of a programming question than a math one. Note that the right shift >> is sign-extending in the C language. Then, assuming an int is 32-bit wide:

                   // if a >= 0          // if a < 0

int t = a >> 31;   // t = 0              // t = 0xFFFFFFFF = -1
a = (a^t) - t;     // a = (a^0)-0 = a    // a = (a^(-1))-(-1) = ~a + 1 = -a


[ EDIT ]  Strictly speaking, the right-shift behavior is implementation defined in both C and C++, though (emphasis mine):

For negative a, the value of a >> b is implementation-defined (in most implementations, this performs arithmetic right shift, so that the result remains negative).

This is, however, a matter better suited to discuss next door at stackoverflow.com.