Search code examples
floating-pointluauint32

How do I convert userdata to a uint32 or float?


How do I convert user data like this:

local user_data = { 0x33, 0x22, 0x11, 0x00 }

to either a uint32 or float using Lua? I cant find anything in the documentation that talks about this.

I've tried various methods and none of these have worked:

local data_uint32 = tonumber(user_data)
local data_uint32 = user_data:uint32()
local data_uint32 = uint32(user_data)

Solution

  • I'd rather define my own function:

    function toUInt32(user_data)
        return user_data[1] * 0x1000000
             + user_data[2] * 0x10000
             + user_data[3] * 0x100
             + user_data[4]
    end
    print(toUInt32(user_data))
    

    Don't know any predefined library function to do this.

    Note: You may want to consider the endianness of the number.