### Bitwise operators

I'm trying to write a simple code (just for learning) to count the number of bit of unsigned int type and I am encountering some problems with Bitwise shift operators.

For example:
 123456789 unsigned short int USI = 0; unsigned int UI = 0; unsigned short int aux = 16; USI = ~USI; cout << "1: " << (((USI) >> aux) != 0 ) << "\n"; cout << "2: " << ((USI) >> aux) << "\n";

gives:
 12 1: 0 2: 0

as it is supposed to do.

But:
 12345 UI = ~UI; aux = 32; cout << "3: " << ( ((UI) >> aux) != 0 ) << "\n"; cout << "4: " << ((UI) >> aux) << "\n";

gives:
 12 3: 1 4: 4294967295

while i expect:
 12 3: 0 4: 0

I'm under ubuntu 12.04 64 bit and g++ --version: g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

Brax
From the C++ Standard:

 The behavior is undefined if the right operand is negative, or greater than or equal to the length in bits of the promoted left operand.

So in the second case that is when UI is used the behavior is undefined because it seems that sizeof( int ) on your system is equal to 4 (* 8 bits = 32 )
Last edited on
It also looks like his implementation is using 64 bit integers.
I would like to add that in the first case there is no undefined behavior due to integer promotion.
Thank you all for your responses.

@guestgulkan:
 12 cout << "5: " << sizeof(int)*8 << "\n"; cout << "6: " << sizeof(short)*8 << "\n";

gives:
 12 5: 32 6: 16

So I think the compiler uses 32 bit integer.

Thank for your explanation: i didn't know it.
Now I'm studying integer promotion. I think that integer promotion should explain likewise the following example:
 12345 unsigned short int USI = 0; unsigned short int aux = 16; //USI = ~USI; cout << "1: " << ( ((~USI) >> aux) != 0 ) << "\n"; cout << "2: " << ((~USI) >> aux) << "\n";