Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set most significant bit in C

I am trying to set the most significant bit in a long long unsigned, x. To do that I am using this line of code:

x |= 1<<((sizeof(x)*8)-1);

I thought this should work, because sizeof gives size in bytes, so I multiplied by 8 and subtract one to set the final bit. Whenever I do that, the compiler has this warning: "warning: left shift count >= width of type"

I don't understand why this error is occurring.

like image 523
Taylor Avatar asked Jul 05 '15 18:07

Taylor


Video Answer


2 Answers

The 1 that you are shifting is a constant of type int, which means that you are shifting an int value by sizeof(unsigned long long) * 8) - 1 bits. This shift can easily be more than the width of int, which is apparently what happened in your case.

If you want to obtain some bit-mask mask of unsigned long long type, you should start with an initial bit-mask of unsigned long long type, not of int type.

1ull << (sizeof(x) * CHAR_BIT) - 1

An arguably better way to build the same mask would be

~(-1ull >> 1)

or

~(~0ull >> 1)
like image 167
AnT Avatar answered Oct 23 '22 23:10

AnT


use 1ULL << instead of 1 <<

Using just "1" makes you shift an integer. 1ULL will be an unsigned long long which is what you need. An integer will probably be 32 bits and long long probably 64 bits wide. So shifting:

1 << ((sizeof(long long)*8)-1)

will be (most probably):

1 << 63

Since 1 is an integer which is (most probably) 32 bits you get a warning because you are trying to shift past the MSB of a 32 bit value.

like image 7
Artur Avatar answered Oct 24 '22 01:10

Artur