Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange result with bitshift operations

Tags:

c

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!

like image 875
MaSmi Avatar asked Dec 04 '11 18:12

MaSmi


People also ask

What happens when you Bitshift?

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.

What is a Bitshift operation?

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 is incorrect for Bitwise operator?

Which of these is not a bitwise operator? Explanation: <= is a relational operator.

What does bit shifting by 0 do?

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 .


2 Answers

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!

like image 69
FailedDev Avatar answered Oct 17 '22 05:10

FailedDev


The expressions are evaluated as (unsigned) ints. (default int promotion). Casting(truncation) to a narrower type only happens just prior to the final assignment.

like image 34
wildplasser Avatar answered Oct 17 '22 05:10

wildplasser