Monday, March 15, 2010

Bump into Shift Operation Oddity

Recently, we bumped into an odd behavior on a shift operation. A code we were debugging was doing a left shift on an integer (1) for 125 times. We were expecting the result to be 0 but oddly the result was 536870912. After consulting our friend Google, we got this explanation:

C99 standard, section 6.5.7 "Bitwise shift operators",
page 84:
"If the value of the right operand is negative or is
greater than or equal to the width of the promoted left
operand, the behavior is undefined."

Apparently, the operation was undefined and the behavior is implementation specific. We tried running the code in C and Java; and found out that if the operator is greater than the operand, in this case the size of the operand is 32, the operand is shifted by "operator modulo size-of-operand" times (1 % (125 mod 32)).

I guess we learn new things everyday! ^_^

No comments: