Zero-fill right shift (>>>)


#1

Hi there,

I see that Defold has its own lib for bitwise operations (https://www.defold.com/ref/bit)
I’m wondering what’s the equivalent for >>> (Zero-fill right shift) from JavaScript.

Apparently LuaBit has this method, which has the following signature:

-- LuaBit's zero-fill right shift
bit.blogic_rshift(n, bits) -- logic right shift(zero fill >>>)

More info:

Any help is appreciated!

Cheers,
Endel


#2

Haven’t tested yet, but I think this adaptation should do (original source: https://github.com/asim/dcpu16-lua/blob/e15e7c8032cf82efc56de0b52bc6cb02224ca7a5/bit.lua#L184-L195)

-- logic rightshift assures zero filling shift
local function bit_logic_rshift(n, bits)
 if(n < 0) then
  n = bit.bnot(math.abs(n)) + 1
 end
 for i=1, bits do
  n = n/2
 end
 return math.floor(n)
end

#3

bit.rshift is the equivalent of >>> from JavaScript. From the Mozilla API doc you linked:

9 >>> 2 is 2
-9 >>> 2 is 1073741821

And doing the same using bit.rshift:

print(bit.rshift(9, 2)) -- 2
print(bit.rshift(-9, 2)) -- 1073741821

#4

bit.rshift(x, n) (https://www.defold.com/ref/bit/#bit.rshift)

“Returns the bitwise logical right-shift of its first argument by the number of bits given by the second argument. Logical shifts treat the first argument as an unsigned number and shift in 0-bits.”

So:

bit.rshift(0x87654321, 12)   --> 0x00087654

#5

Hey there, thanks for the insights!

In the surface it seems the same thing, but I’m having different results here. :cry:

// JavaScript
(-2086820524 >>> 0)
// output: 2208146772
-- Lua
local bit = require("bit")
print(bit.rshift(-2086820524, 0))
-- output: -2086820524
print(bit_logic_rshift(-2086820524, 0))
-- output: -2086820524

I’m still trying to figure out what’s going on. Please let me know if you guys have any clue!

Cheers,
Endel


#6

I can’t really explain, but this has the same result as in JavaScript

bit.rshift(sum3, 1) * 2
-- output: 2208146772

:man_shrugging:


#7

That is the defined behavior in javascript. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Unsigned_right_shift

”This operator shifts the first operand the specified number of bits to the right. Excess bits shifted off to the right are discarded. Zero bits are shifted in from the left. The sign bit becomes 0, so the result is always non-negative.