Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

c - Unexpected output when executing left-shift by 32 bits

When I do a left shift of a hex I get -1 as output with the following code:

unsigned int i,j=0;
i= (0xffffffff  << (32-j));
printf("%d",i);

Similarly when I changed the shift value to 32, the output is 0, but I get warnings from compiler as (left shift count >= width of type)

unsigned int i,j=32;
i= (0xffffffff  << (32));
printf("%d",i);

I was expecting the same results in both the cases (ie, 0), but got confused why is displaying wrong output in case #1, and in case #2 the result is correct but the compiler warns!

The result is same in 32 and 64 bit x86 machines.

Can someone explain the results above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's undefined behavior to left-shit 32 or greater on a 32-bit integer. That's what the error is about.

C11 6.5.7 Bitwise shift operators

The integer promotions are performed on each of the operands. The type of the result is that of the promoted left operand. 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...