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
465 views
in Technique[技术] by (71.8m points)

c - Shifting a 32 bit integer by 32 bits

I'm slinging some C code and I need to bitshift a 32 bit int left 32 bits. When I run this code with the parameter n = 0, the shifting doesn't happen.

int x = 0xFFFFFFFF;
int y = x << (32 - n);

Why doesn't this work?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Shift at your own peril. Per the standard, what you want to do is undefined behavior.

C99 §6.5.7

3 - 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.

In other words, if you try to shift a 32bit value by anything more than 31 bits, or a negative number, you're results are undefined.


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

...