将Hex添加到lua中的字节表

时间:2011-02-03 16:50:08

标签: lua

我有以下十六进制C0010203我需要将它以字节存储在字节表

我忘了我记得的语法

bytes={}
bytes={0xC0 , something here}
 or 
bytes = {something here, 0xC0}

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

我的意思是:

s="C001020304"
t={}
for k in s:gmatch"(%x%x)" do
    table.insert(t,tonumber(k,16))
end

答案 1 :(得分:0)

我有点不清楚你的意思,这样的事情?

tomte@tomte ~ $ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> bytes={}
> bytes["something here"]=0xC0
> print(bytes["something here"])
192
>

编辑: 我看,可能是原始但工作的解决方案(没有边界检查,你必须调整没有偶数长度或不包含十六进制数字的字符串的代码);

tomte@tomte ~ $ lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> i=1
> j=1
> t={}
> s="C0010203"
> while true do
>> t[j] = 0 + ("0x" .. string.sub(s,i,i+1))
>> j=j+1
>> i=i+2
>> if(i>string.len(s)) then break end
>> end
> print (t[1])
192
> print (t[2])
1
> print (t[3])
2
> print (t[4])
3

答案 2 :(得分:0)

在Lua中没有“字节表”。但是,有一个表格,其中字节为数字。

bytes={0xC0, 0x01, 0x02, 0x03}

以下是其他一些选择:

--A table with the bytes as numbers in little-endian:
bytes={0x03, 0x02, 0x01, 0xC0}

--A string of characters that contain the bytes:
bytes=string.char(0xC0, 0x01, 0x02, 0x03)

--A string of characters that contain the bytes in little-endian:
bytes=string.char(0x03, 0x02, 0x01, 0xC0)

--A table of single character strings for each byte:
bytes={string.char(0xC0),string.char(0x01),string.char(0x02),string.char(0x02)}

--A table of single character strings for each byte in little-endian:
bytes={string.char(0x03),string.char(0x02),string.char(0x01),string.char(0xC0)}