I am trying to understand bishift operations better so I wrote myself a little program.
unsigned char a = 240;
a= (a << 3) >> 7;
printf("a: %u\n",a);
Now I would imagine that the result would be something like :
11110000 // 240
10000000 // << 3
00000001 // >> 7
So 1, but I get 15. I am confused... Any help is appreciated!
A bit-shift moves each digit in a number's binary representation left or right. Within right-shifts, there are two further divisions: logical right-shift and arithmetic right-shift. A left-shift is represented by the << operator, while a right-shift is represented by the >> operator.
Bit shifting is an operation done on all the bits of a binary value in which they are moved by a determined number of places to either the left or right. Bit shifting is used when the operand is being used as a series of bits rather than as a whole.
Which of these is not a bitwise operator? Explanation: <= is a relational operator.
1 in binary is 0001 , then bitshifting it by 0 won't do anything, which aligns with what you observed. So any number x << 0 is equivalent to x * 2^0 , which is x * 1 , which is just x .
Your problem is that this statement : (a << 3)
converts the input to an int
. So at this point you have 240 * 2 ^ 3 = 1920
00000000000000000000011110000000
Then you are dividing the previous result by 2 ^ 7 = 128
so you have : 15
00000000000000000000000000001111
Which is exactly what you are getting as a result.
If you wanted to truncate bits you could have used :
printf("a: %u\n",a & 1); //get only last bit so you would have 1 as a result!
printf("a: %u\n",a & 255); //get all 8 bits
Hope this helped!
The expressions are evaluated as (unsigned) ints. (default int promotion). Casting(truncation) to a narrower type only happens just prior to the final assignment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With