Thomas
Thomas

Reputation: 1105

>> and << and data types in C++

I have looked over the guide given in this answer, but I still don't understand bit-shifting. In particular I am confused about the data types come into play.

The following:

unsigned int a = pow(2,31);
cout << (a << 1);

indeed produces 0 as I expect because the int is 32 bits, so moving the 1 to the left, pushes it into nothing.

But the following

unsigned int a = 1;
unsigned char b = (unsigned char)a;
cout << (unsigned int)(b<<8);

produces 256. Why is that? My guess would have been that a char is 8 bit and so moving 1 left 8 places should give zero.

Is there a function/shift that does this? (i.e. evaluates 1<<8 to 0).

Upvotes: 1

Views: 89

Answers (1)

K-ballo
K-ballo

Reputation: 81349

Narrow integral values are promoted to int or unsigned int before being used. It's called integral promotion.

Upvotes: 7

Related Questions