我有几个十六进制值,我尝试写入文件.似乎Lua不支持开箱即用,因为它们都被视为字符串而不是值.我想我必须将更长的十六进制值分解,例如将AABBCC分解为AA,BB,CC并连续使用所有十进制值的string.char()来完成工作.
是否有内置函数允许我直接编写这些值而不先进行转换?我使用了诸如"0xAA"和"\ xAA"之类的转义字符,但是那些没有用完.
编辑:让我举个例子.我在十六进制编辑器中查看测试文件:
00000000 00 00 00 00 00 00 ......
Run Code Online (Sandbox Code Playgroud)
我想用以下方式用字母"AABBCC"写它:
00000000 AA BB CC 00 00 00 ......
Run Code Online (Sandbox Code Playgroud)
我通过转义字符获得的是:
00000000 41 41 42 42 43 43 AABBCC
Run Code Online (Sandbox Code Playgroud)
Mic*_*man 27
我使用以下函数在十六进制字符串和"原始二进制"之间进行转换:
function string.fromhex(str)
return (str:gsub('..', function (cc)
return string.char(tonumber(cc, 16))
end))
end
function string.tohex(str)
return (str:gsub('.', function (c)
return string.format('%02X', string.byte(c))
end))
end
Run Code Online (Sandbox Code Playgroud)
它们可以如下使用:
("Hello world!"):tohex() --> 48656C6C6F20776F726C6421
("48656C6C6F20776F726C6421"):fromhex() --> Hello world!
Run Code Online (Sandbox Code Playgroud)