homior
homior

Reputation: 191

The right order of shifting bits in c

What is the difference and why are there 3(???) different results?

signed char b;
b = 66 << 2 >> 8;
fprintf(stdout, "%d\n", b);

Output: "1"

signed char b;
b = 66 << 2;
b = b >> 8;
fprintf(stdout, "%d\n", b);

Output: "0"

signed char b;
b = 2 >> 8;
b = 66 << b;
fprintf(stdout, "%d\n", b);

Output: "66"

thanks for help!

Upvotes: 0

Views: 50

Answers (1)

glglgl
glglgl

Reputation: 91059

signed char b = 66 << 2 >> 8;

Here, 66 << 2 becomes a signed int 264 (signed int because it is an intermediate result), which is shifted >> 8, which becomes 1.

signed char b = 66 << 2;

Here, the 264 (same as above) is "pressed" into a signed char, turning it to 8. Applying >> 8 here results in 0.

Well, and your 3rd example, 2 >> 8 is obvously 0, so the 66 is left unchanged.

Upvotes: 3

Related Questions