在lua中将字符串转换为十六进制? [英] convert string to hex in lua?
问题描述
我打算通过套接字发送一个字节数组,但我曾经在c / c ++中工作过,并且对lua是新手。
现在我有一个问题,这里是我的问题。
我想发送一个bytearray.It应该包含mac_address,string_length,string。
详细信息:
mac_address:6字节
字符串长度:1字节
字符串:几个字节
(1)第一个问题
现在,我有一个像01:2f:c2:5e:b6:a3的mac_address字符串,怎么可以我将它转换成一个6字节的十六进制数组?
(2)second
如何定义一个无符号数并将其存储为字节?例如,sting_length是33,如何将它作为0x21存储到一个字节中?
<3> last
如何将mac_address(6bits),string_length(1bit),data_string (例如100bytes)转换成字节数组,并成功通过luasocket发送出去。
就是这样。
<您可以使用
> string.char
来 得到一个数字的符号表示,这将允许您将数字打包到b中ytes。这样的东西应该可以工作:$ b $ pre $
本地函数包(地址,str)
返回地址:gsub((%函数返回string.char(tonumber(s,16))end)
.. string.char(#str)
.. str
end
print(packet(10:2f:c2:5e:b6:a3,abc)==\16 \\\\\\'\\'\\\\\\' )
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! You can use 这篇关于在lua中将字符串转换为十六进制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! gsub
将地址中的每个组, tonumber(s,16)
将十六进制数转换为十进制数, string.char
将其转换为一个字符一个字节)表示。然后将它们一起打包成一个可以发送的字符串。这是结果字符串的Lua表示形式:\16 / \\\\\\\\\\' b
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"
.