Log In  


shr(x,n) and lshr(x,n) have always handled shift values outside the 0…31 range in a peculiar way: negative values of n are treated like n&31, while values ≥ 32 always return 0 (or 0xffff.ffff for a signed shift).

But now the new >>> operator diverges from lshr by treating n ≥ 32 like n&31, so we get:

   1 >> 32 = 0
 shr(1,32) = 0
  1 >>> 32 = 1
lshr(1,32) = 0

edit: same with << which no longer behaves like shl()

1


Oof, that's not good. I hope it's just a bug.

@zep
Same thing happens if the shift value is a variable, so it's not just an opcode encoding issue with immediate values.


Thanks @samhocevar, that was a timely catch -- fixed for 0.2.0f

I think it's worth the low risk of breakage to do something better for negative shift values too. To follow suit with the n >= 32 behaviour I suppose shl(x, -n) should give the same result as lshr(x, n) and vice versa, as Lua 5.3 does. It's not the best for porting / transpiling to non-Lua languages, but oh well.


1

I also like the idea of negative shifts Just Working™, as it makes a lot of stuff work without needing any ugly branching.


extra note: negative shift values round down, same as rotl, rotr. so when n < 0:

shl(x, n) == lshr(x, -(n\1))
shr(x, n) == lshl(x, -(n\1))
lshr(x, n) == lshl(x, -(n\1))

@zep

That makes sense. Intuitively I'd expect the fractional bits to be ignored, effectively the same as rounding down.


@zep I don’t think I understand the new 0.2.0f logic wrt. overflows:

?7 << 256
0
?7 << -256
7
?7 >> 256
0
?7 >> -256
0
?7 >>> 256
7
?7 >>> -256
0

(also they can now crash/freeze as reported in https://www.lexaloffle.com/bbs/?tid=37768)


WHAT

ok, 0.2.0f doesn't exist. It's correct in 0.2.0g which is up now.



[Please log in to post a comment]