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.
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.
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.
What is the reason for this difference?
The 1st snippet returns the result of adding two unsigned
s with the result being (implicitly) converted to an int
.
The 2nd snippet returns the result of adding two int
s .
More on "The Usual Arithmetic Conversions":
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