convert string to hex in lua?

12,987

You can use string.char to get a symbol representation of a number, which will allow you to pack numbers into bytes. Something like this should work:

local function packet(address, str)
  return address:gsub("(%x+):?",function(s) return string.char(tonumber(s, 16)) end)
  .. string.char(#str)
  .. str
end
print(packet("10:2f:c2:5e:b6:a3", "abc") == "\16/\194^\182\163\3abc")

gsub takes every group in the address, tonumber(s, 16) converts the hex number into a decimal and string.char converts it into a character (one-byte) representation. It's all then packed together into one string that can be sent. This is the Lua representation of the resulting string: "\16/\194^\182\163\3abc".

Share:
12,987
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin 6 months

    I am going to send a byte array through socket.But I used to work in c/c++ and be new to lua. Now i have a problem,here is my question.

    i want to send a bytearray.It should contain mac_address,string_length,string.

    For detail:

    mac_address:6 bytes length of string: 1 byte string:several bytes

    (1)first question Now,I have a string of mac_address like“01:2f:c2:5e:b6:a3”,how can I convert it into a 6 byte hex array?

    (2)second how to define an unsigned number and store it to byte?for example,sting_length is 33,how can i store it as 0x21 into a byte?

    (3)last how to combine mac_address(6bits),string_length(1bit),data_string(for example,100bytes) into a byte array,and successfully send it out through luasocket.

    that's all.

    Thank you!