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:
1
2
3
4
5
6
7
8
9
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:
1
2
1: 0
2: 0

as it is supposed to do.

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


gives:
1
2
3: 1
4: 4294967295

while i expect:
1
2
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

Thanks in advance.

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:
1
2
cout << "5: " << sizeof(int)*8 << "\n";
cout << "6: " << sizeof(short)*8 << "\n";

gives:
1
2
5: 32
6: 16

So I think the compiler uses 32 bit integer.

@vlad from moskow
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:
1
2
3
4
5
unsigned short int USI = 0;
unsigned short int aux = 16;
//USI = ~USI;
cout << "1: " << ( ((~USI) >> aux) != 0 ) << "\n";
cout << "2: " << ((~USI) >> aux) << "\n";

that instead returns:
1
2
1: 1
2: -1

Thanks in advance.

Brax
Topic archived. No new replies allowed.