Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Odd bit shifting behavior

I have the following C code which works:

int ex(unsigned int x) {     int mask  = 0x55555555;     int a = ((x >> 0) & mask );     return a + ((x >> 1) & mask ); } 

However, when I expand it to this, I get a different result:

int ex(unsigned int x) {     int mask  = 0x55555555;     int a = ((x >> 0) & mask );     int b = ((x >> 1) & mask );     return a + b; } 

What is the reason for this difference?

EDIT: Note, I'm compiling this for 32bit.

like image 397
cdignam Avatar asked Sep 22 '17 15:09

cdignam


People also ask

What does shifting bits left one place do?

Logical bit shifting may be useful for multiplying or dividing unsigned integers by powers of two. For example, if the value "0001" or "1" is shifted left, it becomes "0010" or "2," shifted to the left again it becomes "0100," or "4." Shifting to the right has an opposite effect of dividing the value by two per shift.

Why would you want to shift bits?

Bit shifts help with optimization in low-level programming because they require fewer calculations for the CPU than conventional math. Bit shifting operations may be declared explicitly by the programmer, or automatically by the compiler if it can identify that such an optimization is possible.


1 Answers

What is the reason for this difference?

The 1st snippet returns the result of adding two unsigneds with the result being (implicitly) converted to an int.

The 2nd snippet returns the result of adding two ints .


More on "The Usual Arithmetic Conversions":

  • Usual arithmetic conversions in C : Whats the rationale behind this particular rule
  • C usual arithmetic conversions
  • Implicit integer type conversion in C
like image 123
alk Avatar answered Sep 19 '22 23:09

alk