warning: left shift count >= width of type

CBit ManipulationLong IntegerBit Shift

C Problem Overview


I'm very new to dealing with bits and have got stuck on the following warning when compiling:

> 7: warning: left shift count >= width of type

My line 7 looks like this

unsigned long int x = 1 << 32;

This would make sense if the size of long on my system was 32 bits. However, sizeof(long) returns 8 and CHAR_BIT is defined as 8 suggesting that long should be 8x8 = 64 bits long.

What am I missing here? Are sizeof and CHAR_BIT inaccurate or have I misunderstood something fundamental?

C Solutions


Solution 1 - C

long may be a 64-bit type, but 1 is still an int. You need to make 1 a long int using the L suffix:

unsigned long x = 1UL << 32;

(You should also make it unsigned using the U suffix as I've shown, to avoid the issues of left shifting a signed integer. There's no problem when a long is 64 bits wide and you shift by 32 bits, but it would be a problem if you shifted 63 bits)

Solution 2 - C

unsigned long is 32 bit or 64 bit which depends on your system. unsigned long long is always 64 bit. You should do it as follows:

unsigned long long x = 1ULL << 32

Solution 3 - C

The accepted solution is fine for [constant]ULL<<32 but no good for existing variables - e.g. [variable]<<32. The complete solution for variables is: ((unsigned long long)[variable]<<32). Aside: My personal opinion of this warning is that it is totally unnecessary in the first place. The compiler can see what the receiving data type is and knows the width of the parameters from the definitions in headers or constant values. I believe Apple could make the clang compiler a little more intelligent than it is regarding this warning.

Solution 4 - C

unsigned long x = 1UL << 31;

Not show the error message. Because before you specify the 32, is not true because only limited to 0-31.

Solution 5 - C

You can't shift a value to its max bit

int x;         // let int be 4 bytes so max bits : 32 
x <<= 32; 

So, this generates the warning

left shift count >= width of type (i.e type = int = 32 )

Solution 6 - C

You can use something like that:

unsigned long x = 1;
x = x << 32;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRupert Madden-AbbottView Question on Stackoverflow
Solution 1 - CJames McNellisView Answer on Stackoverflow
Solution 2 - CtznzaView Answer on Stackoverflow
Solution 3 - CVectorVictorView Answer on Stackoverflow
Solution 4 - CMuthuramanView Answer on Stackoverflow
Solution 5 - Cvipul baggaView Answer on Stackoverflow
Solution 6 - CJohnView Answer on Stackoverflow