简体   繁体   中英

bit32.band like operation in 64 bits

I want to apply a bitwise AND operation in 64 bits in Lua 5.1. Is there an algorithm for it? (I have no idea on how to do it.)

Note : I only need to operate on 48 bits at total, and I am not having trouble with them.

In the game's Lua I'm scripting there's the bit32 library only.

Lua is using double floating numbers internally by default. It has only 52 bits for mantissa, so you can't safely store 64-bit integers without risking to get invalid floating point values.
With 32 bits it's quite safe. Lua 5.2 manuals describe what happens in bit32 lib with the numbers:

Unless otherwise stated, all functions accept numeric arguments in the range (-2^51,+2^51); each argument is normalized to the remainder of its division by 2^32 and truncated to an integer (in some unspecified way), so that its final value falls in the range [0,2^32 - 1]. Similarly, all results are in the range [0,2^32 - 1].

You'll have to work in 32-bit chunks.
Or maybe introduce your own 64-bits type, probably hosted with userdata, and define 64-bit actions for that type.

local function band48 (x, y)
   local xl = x % 4294967296
   local yl = y % 4294967296
   local xh = (x - xl) / 4294967296
   local yh = (y - yl) / 4294967296
   return bit32.band(xh, yh) * 4294967296 + bit32.band(xl, yl)
end

print(band48(7 * 2^33 + 3, 5*2^33 + 5)) --> 5*2^33+1 = 42949672961

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM