Reputation: 433
I'm working with bitshift for the first time and I'm experiencing unexpected results.
I'm declaring the shift amount as follows:
byte p_size = 0;
if (ver == 0x12 || ver == 0x13)
p_size = 20;
else
p_size = 40;
The value to be shifted is declared as
int t_size = rinput.ReadInt32();
And finally the code I use to shift:
int temp = t_size >> p_size << p_size;
Let's say t_size = 0x2000385E and p_size = 20. temp = 0x20000000 as expected.
Now if t_size = 0x40001014 and p_size = 40, temp = 0x40001000 instead of 0x40000000. I calculated "manually" using a bitwise calculator and it matches the expected result of 0x40000000.
It's probably a silly oversight on my behalf but I don't understand what would cause the weird results with p_size = 40... any advice is appreciated!
Upvotes: 2
Views: 886
Reputation: 100630
Current behavior is expected as 40 & 0x1f is 8 as described in operator >>
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
You probably looking for some masking rather than shifts - maybe
t_size & 0xFF000000
Upvotes: 5
Reputation: 31404
Shifting a 32 integer by 40 bits doesn't really make sense since you would be shifting the integer by more bits than it contains.
Both the left and right shift operators document what they do in this case:
If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand (second operand & 0x1f).
So when p_size
is 40, the shifts are shifting by 40 & 0x1f = 8 bits.
If you need to shift by 40 bits, but your value into long
.
Upvotes: 7