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?
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?
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.
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
- 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).