开发者

Unexpected Outputs in Left Shift Operation...?

开发者 https://www.devze.com 2023-01-21 11:48 出处:网络
I read that Left shift e1<<e2 is equivalent to e1* 2e2. But for the code: x=5; printf(\"%d\",x<<3);

I read that Left shift e1<<e2 is equivalent to e1* 2e2. But for the code:

x=5;
printf("%d",x<<3);

Output is 40 but according to me it should be 30. and for x<<4 it is 80 .(but expected 40).

Although for x<<1 and x<<2 outputs 开发者_StackOverflow中文版are 10 and 20 as expected.

Please explain this logic.


00000101 = 4 + 1 = 5

00101000 = 32 + 8 = 40

Left shift is not successive multiplication by 2, 4, 6, 8 (i.e. x*2)—it's successive multiplication by 2, 4, 8, 16 (i.e. x^2).


No, 40 is quite right...

What you seem to be expecting is this: "x * 2 * n", but left shift is a different operation.

You can think of left shift as an efficient "x * 2^n" where n is the number - in your case 3. So what you're doing is 5 * 8, which is 40.

Same goes for 80: 5 * 16, which is 80.

0

精彩评论

暂无评论...
验证码 换一张
取 消