lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


While writing this up, I already solved this problem by myself, so I guess I'll just send this in case someone else encounters a similar problem, and also to see whether there are better solutions.

From the luajit API specification:
All bit operations are thus defined to return results in the range of signed 32 bit numbers (converted to the Lua number type).

In other words:

> =bit.bnot(0x00000000)
-1


When only using luajit bitops, there will be no problems with this. However, the moment one starts treating bit fields as unsigned integers in their own functions, problems arise. For instance, I'm using luajit to prototype some C code which uses bitscan. I thus defined a bitscan function as follows:


function rawBitScanR(num)
  return math.floor(math.log(num) / math.log(2)) + 1
end

> =rawBitScanR(0xFFFFFFFF)
32
> =rawBitScanR(bit.bnot(0x00000000))
nan

I could only think of one way to get my function to work again: By manually converting the results to positive values.

function make_unsigned(num)
  if num < 0 then
    return 0xFFFFFFFF + num + 1
  else
    return num
  end
end

> =rawBitScanR(make_unsigned(bit.bnot(0x00000000)))
32

If there are better solutions, I'd be glad to hear them.