shift - Bitshifting in C++ producing the wrong answer -
i tried running following code code:
char c = (2 << 7) >> 7 which should return 0 because 2 has binary representation char:
0 0 0 0 0 0 1 0 after 7 shifts left,
0 0 0 0 0 0 0 0 then, after 7 shifts right, get
0 0 0 0 0 0 0 0 however, i'm getting result 2, not 0.
the compiler says 2 << 7 256, it's char , shouldn't 256.
i understand 2 << 7 calculated ints , answer put c 256 >> 7 2.
i tried cast 2 char (ex: (char)2>>7) doesn't work either.
i'm trying extract each bit char, wrote code:
char c = 0x02; for(int i=0;i<7;i++) { char current = (c<<i)>>7; } how can each bit? what's wrong way?
the result of arithmetic shift operation 1 operand being int in c++ int. therefore, when write
current = (c << i) >> 7; c++ interpret (c << i) , (c << i) >> 7 ints, casting char when assignment done. since temporary values ints, no overflow occurs , result should come out integer result casted char.
hope helps!
Comments
Post a Comment