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?
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?
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 anintis 32-bit wide:[ EDIT ] Strictly speaking, the right-shift behavior is implementation defined in both C and C++, though (emphasis mine):
This is, however, a matter better suited to discuss next door at stackoverflow.com.