Shift bit left and right bug
-
Hello there is a bug with shiftLeft and shiftRight with big value.
For exemple, i want to extract a number in a hexadecimal value, here i want to extract the A (= 10 in decimal) of 0xA0000000 i use this code :
instr = 0xA0000000 type = (instr&0xF0000000)>>28 loop clear() print(type) update() repeat
This code work ! tested in C language
But here type is corrupted, normaly type= 10.To fix.
-
I have raised an issue for this
-
This is actually not so much 'corruption' as it is due to the use of signed 32 bit integer literals. As a signed 32 bit value both
0xA0000000
= -1610612736 and0xF0000000
have the sign bit set.Fuze converts the 32 bit signed literals into 64 bit signed values when assigned to variables and to do the arithmetic. The intermediate values have all of the upper 32 bits set to 1, because the 2's complement representation extends the value of the sign bit into the new bit positions.
Because the 64 bit values are also signed, Fuze uses a signed right shift, also known as an arithmetic right shift rather than an unsigned or logical right shift. The arithmetic right shift works by copying the sign bit into each bit position without another input. The result is that
type
has the value -6, which has the same last four bits as 10 has but the first 60 bits are all 1's instead of all 0's.Is this a bug? I don't know. It is very awkward that Fuze uses a smaller type for literals than variables. However in this case the main confusion arises from the use of signed numbers with the sign bit set. Right-shift (
>>
) only generates 0's in the case when there is no sign bit or when it is not set. -
I think Gothon already nailed the answer, but I'd just like to add that JavaScript has both the
right-shift
operator>>
and theunsigned right-shift
operator>>>
.So you could experiment with the difference between the two in your browsers developer toolbar.
You'd see that(0xA0000000&0xF0000000) >> 28
also results in -6 in JavaScript, but(0xA0000000&0xF0000000) >>> 28
does result in 10. -
I don’t understand enough about this to comment meaningfully myself, but if one of you could comment about workarounds or ‘usage guidelines’ or whatever, I would be interested to read. Seems as if you know all about this stuff already.