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

前端 未结 3 1559
广开言路
广开言路 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:25

    my suggestion for an "Int16ToByte"-function without checking of parameters:

    function Int16ToBytes(num, endian)
      if num < 0 then 
          num = num & 0xFFFF
      end
    
      highByte = (num & 0xFF00) >> 8
      lowByte  = num & 0xFF
    
      if endian == "little" then
          lowByte, highByte = highByte, lowByte
      end
    
      return string.char(highByte,lowByte)
    end
    

提交回复
热议问题