luanumbersbytebit16-bit

Reading a signed bits in Lua


I have a 16-bit in a string but this is the representation of a signed number. Is there a way/function that do the converson from signed bits to decimal ?

The function tonumber() assumes the bits are unsigned.


Solution

  • Lua 5.3/5.4

    Use string.unpack with a format string <i2 to read the binary string. (use >i2 for big endian data)

    --0x8000 ---> -32768
    local v = string.unpack('<i2', '\x00\x80')
    

    Lua 5.2/5.1

    There is no string.unpack, so you have to read each byte of the string, then compute the value manually.

    local l, h = string.byte('\x00\x80', 1, 2)
    local v = h * 256 + l --big endian: v = l * 256 + h
    if v > 32767 then v = v - 65536 end