Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - bit shifting with unsigned long type produces wrong results

I'm a bit confused because I wanted to initialize a variable of type unsigned long whose size is 8 bytes on my system (on every modern system I suppose). When I want to assign 1 << 63 to the variable, I get a compiler warning however and the number is in fact 0. When I do 1 << 30 I get the expected result of 2 ^ 30 = 1073741824. Yet when I do 1 << 31, I get the result of 2 ^ 64 (I think; actually this shouldn't be possible) which prints 18446744071562067968.

Can anyone explain this behaviour to me?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

1 << 63 will be computed in int arithmetic, and your int is probably 32 bit.

Remedy this by promoting one of the arguments: 1ULL << 63 will do it.

ULL means the expression will be at least 64 bits.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...