'convert string to hex in lua?
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!
Solution 1:[1]
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".
Solution 2:[2]
function hexbyte(a,b)
b1=string.byte(a)
b2=string.byte(b)
result = 0 
  if (b1 >= string.byte('A')) then
     result = 16*result + b1 - string.byte('A') +10
           else
     result = 16*result + b1 - string.byte('0')
  end
  if (b2 >= string.byte('A')) then
     result = 16*result  + b2 - string.byte('A') +10
  else
     result = 16* result + b2 - string.byte('0')
 end
 return string.format('%02X', (result))
 end 
    					Solution 3:[3]
This works for me:
local function PrintHex(data)
    for i = 1, #data do
        char = string.sub(data, i, i)
        io.write(string.format("%02x", string.byte(char)) .. " ")
    end
end
    					Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source | 
|---|---|
| Solution 1 | |
| Solution 2 | Naeem Ul Hassan | 
| Solution 3 | Martin MlĂch | 
