user2803482 user2803482 - 4 years ago 119
C Question

print(1 >> (10 ^ 0xAAAA)) is 0. However, it is different in c language

For python:

print(1 >> (10 ^ 0xAAAA))

The result is 0.

For c language:

int main(int argc, const char * argv[]) {
long int x=10;
long int a = x ^ 0xAAAA;
int b = 1 >> a;
printf("a: %x\n", a);
printf("b: %d\n", b);

The result b=1.

For x=1,100 etc.. The outputs of python and c codes are all 0.
Given x=10, the outputs are different.

Answer Source

In Python you can right shift as much as you want, and it'll give you always the correct result (which, for a shift amount big enough, will always be zero); in C instead right-shifting of more than the type size is undefined behavior (C99, §6.5.7 ¶3; the same holds for the left shift), which means that the compiler is free to emit code that does anything in that particular case.

The point of having undefined behavior in all "strange cases" of bit shifting is to let the compiler translate shifts in C code straight to whatever shift instructions the target platform provides and obtain the best performance; in your particular case, probably you are running your program on x86, where the C right shift gets translated straight to a SHR or SAR instruction. These take only the low 5 bits of the shift amount, so it becomes a right shift of zero places, hence the result.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download