Search code examples
tcplua

How do I convert string to a uint32 and send it to server in Lua?


I want to use lua to send tcp messages to the server. The server requests to send a little-endian uint32 byte stream to it. But my lua doesn't have string.pack and string.unpack. How to achieve it with only lua but not c?

My opinion is: 1.converts not in uint32 format to uint32

function UIUtils.GetStr2ID(strID)
    return (string.byte(strID, 1) << 24) | (string.byte(strID, 2) << 16) | (string.byte(strID, 3) << 8) | (string.byte(strID, 4))
end

2.change it to little-endian

I want to know how to solve this problem.


Solution

  • Your question is very unclear. Do you want:

    1. Conversion from number ("uint32") to bytestring (little endian? network byte order usually is big endian)
    2. Conversion from (little endian) bytestring to number ("uint32")
    3. Conversion from big endian to little endian byte strings and vice versa can trivially be done using str:reverse() where str is a string.

    Number to Bytestring

    Output is a little endian 4-byte-string.

    local floor = math.floor
    local function uint32_to_bytestr(n)
        assert(n % 1 == 0 and n >= 0 and n < 2^32, "n does not fit in a uint32")
        return ("%c%c%c%c"):format(
            n % 0x100,
            floor(n / 0x100) % 0x100,
            floor(n / 0x10000) % 0x100,
            floor(n / 0x1000000) % 0x100
        )
    end
    

    Bytestring to Number

    Input is a little endian 4-byte-string, output is a number from 0 to 2^32-1.

    local function bytestr_to_uint32(str)
        assert(#str == 4, "byte string is not 4 bytes long")
        return str:byte(1)
             + str:byte(2) * 0x100
             + str:byte(3) * 0x10000
             + str:byte(4) * 0x1000000
    end