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

bit shift - Bit shifting an int 32 times in C

I have a specific C bit-shifting scenario that I do not believe is covered on Stack Overflow yet. (If it is, I haven't been able to find it!)

This exercise is using signed ints as the data type.

Take the value 0x80000000 (which is just a 1 in the most significant bit.)

Shift it right once on a machine using arithmetic right-shifts (which mine does).

Result = 0xC0000000 (1100 0000 in leftmost byte).

Continue shifting it and you should be filling up with ones, from the left to the right.

Result = 0xFFFFFFFF (All ones.)

However: Try the same example but shift one extra position, all together:

0x80000000 >> 0x00000020 (Right shift 32 times)

Your result? I don't know. My result was not all ones. In fact, I got 0x00000001 which was NOT my desired behavior. Why is this? Is it machine specific?

(Context: Homework assignment limiting my operations to a few bit operators to solve a puzzle. This is an aspect to a puzzle but is far from the entire question.)

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

Why doesn't left bit-shift, "<<", for 32-bit integers work as expected when used more than 32 times?

which means you should avoid it like the plague. Here's some links including "What every C programmer should know about undefined behavior": http://lwn.net/Articles/511767/


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

...