在Lua中的字节表中添加十六进制。

我有以下十六进制值 C0010203,我需要将其存储为字节数组在一个字节数组表中。

我忘记了语法,但我记得:

bytes={}
bytes={0xC0,这里有些东西}
或
bytes = {这里有些东西,0xC0}

感谢帮助。

原文链接 https://stackoverflow.com/questions/4889003

点赞
stackoverflow用户594138
stackoverflow用户594138

我不太清楚你的意思,是这样的吗?

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

编辑: 我明白了,这可能是一个简单而有效的解决方案(没有边界检查,你必须调整代码以适应长度不均匀或不包含十六进制数字的字符串);

tomte@tomte ~ $ lua
Lua 5.1.4  版权所有 (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
2011-02-03 16:58:22
stackoverflow用户513763
stackoverflow用户513763

我的实现:

s="C001020304"
t={}
for k in s:gmatch"(%x%x)" do
    table.insert(t,tonumber(k,16))
end
2011-02-03 19:21:44
stackoverflow用户173806
stackoverflow用户173806

在 Lua 中没有"字节表"。但是,有一个包含字节作为数字的表。

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

以下是其他选项:

--一个以小端序列表示字节的表:
bytes={0x03, 0x02, 0x01, 0xC0}

--包含字节的字符字符串:
bytes=string.char(0xC0, 0x01, 0x02, 0x03)

--包含字节的小端序字符字符串:
bytes=string.char(0x03, 0x02, 0x01, 0xC0)

--每个字节的单字符字符串表:
bytes={string.char(0xC0),string.char(0x01),string.char(0x02),string.char(0x02)}

--以小端序表示每个字节的单字符字符串表:
bytes={string.char(0x03),string.char(0x02),string.char(0x01),string.char(0xC0)}
2011-02-05 05:01:33