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

c++ - Why doesn't left bit shift << shift beyond 31 for long int datatype?

I want to use the following code in my program but gcc won't allow me to left shift my 1 beyond 31.

sizeof(long int) displays 8, so doesn't that mean I can left shift till 63?

#include <iostream>

using namespace std;

int main(){
    long int x;
    x=(~0 & ~(1<<63));
    cout<<x<<endl;
    return 0;
}

The compiling outputs the following warning:

left shift `count >= width` of type [enabled by default] `x=(~0 & ~(1<<63))`;
                                                                    ^

and the output is -1. Had I left shifted 31 bits I get 2147483647 as expected of int.

I am expecting all bits except the MSB to be turned on thus displaying the maximum value the datatype can hold.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Although your x is of type long int, the 1 is not. 1 is an int, so 1<<63 is indeed undefined.

Try (static_cast<long int>(1) << 63), or 1L << 63 as suggested by Wojtek.


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

...