help with bitwise operator <<

Hi guys, it's my first post and I'm a beginner with C++.
I know x<<y means: x is shifted by y bit. If y is bigger than the length of x, then bits that are shifted off the end of x should be lost, right?

But I run the following code on vs2008;
1
2
3
4
5
void main()
{
    char b = 1;
    cout << (b << 8) << endl;
}

the result is 256 which means the b(00000001) is somehow converted to 00000001,00000000. The bit shifted off the end is not lost! How could this happen?
Last edited on
The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULLONG_MAX+1 if E1 has type unsigned long long int, ULONG_MAX+1 if E1 has type unsigned long int, UINT_MAX+1 otherwise.
In your implementation, UINT_MAX is greater than 255.
Your assumption would be (mostly) true if you tried to assign the result of the shift back to b. It won't be exactly what you're expecting because b is (most likely) signed.

As an aside, it's generally a bad idea to perform bitwise operations on signed operands. You can get very surprising and probably undesirable results if you do it.
The result you have is correct. To shift left a binary number is equivalent to multiply it by 2
When you write:

 
cout << (b << 8) << endl;



it is equivalent to write

 
cout << (b*2*2*2*2*2*2*2*2) << endl;



and it will print 256 (1*2*2*2*2*2*2*2*2 = 256)


If you want the number 1 to disappear you need to write something like this:

1
2
3
char b = 1;
b = (b << 8);
cout << (int)b << endl;


It will print the 0 you are expecting
Last edited on
@gaorozcoo

I think that wasnt his problem. The problem was that char isnt supposed to hold the value 256.
@Breadman

Which char is holding 256? in his code the variable b is never getting assigned with the result of the shift operation and that is the error.
He is telling the system take b shift it 8 times to the left and print the result, in others words, “cout” does not know that the result to be printed needs to be truncated to 8 bit.
It will print the result of b*2*2*2*2*2*2*2*2 which is 256
Last edited on
oh ye my bad xD. they were talking about it tho
cout << (b << 8) << endl;

The << in the brackets is acting on int values

- the char b is promoted to an int
- this int value is then shifted
- the resultant temporary variable is then being written to the stream

Which is why the output is a number rather than some strange char or other -- as the int overload of ostream::operator<< is being used, rather than the char version).
Last edited on
Topic archived. No new replies allowed.