Reputation: 9292
In a C++ function, I have the following variables:
uint32_t buf = 229; //Member variable
int bufSize = 0; //Member variable
static constexpr const uint32_t all1 = ~((uint32_t)0);
And this line of code:
uint32_t result = buf & (all1 >> (32-bufSize ));
Then the value of result
is 229, both by console output, or by debugging with gdb. The expected value is of course 0, and any trial to make a minimal example reproducing the problem failed.
So I went to the disassembly and executed it step by step. The bit shift operation is here:
0x44c89e <+0x00b4> 41 d3 e8 shr %cl,%r8d
The debugger registers show that before the instruction, rcx=0x20
and r8=0xFFFFFFFF
After the instruction, we still have r8=0xFFFFFFFF
I have a very poor knowledge of x86-64 assembly, but this instruction is supposed to be an unsigned shift, so why the heck isn't the result 0?
I am using mingw-gcc x86-64 4.9.1
Upvotes: 0
Views: 121
Reputation: 1952
Invoke -Wall
on compiler and you will have -Wshift-count-overflow
problem as you are using 32 for shifting which is size of unsigned int. Now you can do one thing just for knowing about it. Change 32 to 31 and compile. Then compare the assembly generated and you will know what went wrong.
The easiest fix for you would be use long
data type for all1
and result
.
Upvotes: 2