I have several hex-values that I try to write to a file. It seems that Lua doesn't support that out of the box, since they are all treated as strings instead of values. I figured I would have to break up a longer hex-value, for example AABBCC into AA, BB, CC and use string.char() on all of their decimal values consecutively to get the job done.
Is there a built in function that allows me to write such values directly without converting them first? I used escape characters such as "0xAA" and "\xAA", but those didn't work out.
Edit: Let me give you an example. I'm looking at a test file in a hex editor:
00000000 00 00 00 00 00 00 ......
And I want to write to it in the following fashion with the string "AABBCC":
00000000 AA BB CC 00 00 00 ......
What I get though with the escape characters is:
00000000 41 41 42 42 43 43 AABBCC
I use the following functions to convert between a hex string and a "raw binary":
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
They can be used as follows:
("Hello world!"):tohex() --> 48656C6C6F20776F726C6421
("48656C6C6F20776F726C6421"):fromhex() --> Hello world!
So you have a string like this:
value = 'AABBCC'
And you want to print it (or turn it into a string) like this?
'101010101011101111001100'
How about this?
function hex2bin(str)
local map = {
['0'] = '0000'
['1'] = '0001'
['2'] = '0010'
-- etc. up to 'F'
}
return str:gsub('[0-9A-F]', map)
end
Note that it leaves untouched any characters which could not be interpreted as hex.
There is so such function because it's that easy to write one.
function writeHex(str,fh)
for byte in str:gmatch'%x%x' do
fh:write(string.char(tonumber(byte,16)))
end
end
This just plainly writes the values to the file pointed to by the fh filehandle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With