Lua, dealing with non-ascii byte streams, byteorder change

前端 未结 3 1528
广开言路
广开言路 2020-12-30 16:11

Need to encode & decode byte-stream (containing non-ascii characters possibly), from/into uint16, uint32, uint64 (their typical C/C++ meaning), taking care of endianness

3条回答
  •  粉色の甜心
    2020-12-30 16:48

    Take a look at the struct and lpack libraries.

    In this example, I use the struct.unpack to decode a Lua string into two integers with forced little-endian encoding:

    require 'struct'
    -- convert character codes to a Lua string - this may come from your source
    local str = string.char(0x00, 0x1d, 0xff, 0x23, 0x44, 0x32)
    -- format string: < = little endian, In = unsigned int (n bytes)
    local u16, u32 = struct.unpack(' 7424    843326463
    

提交回复
热议问题