Lua: writing hexadecimal values ​​as a binary file

I have several hexadecimal values ​​that I am trying to write to a file. Lua does not seem to support this out of the box, as they are all treated as strings instead of values. I decided that I would have to split the longer hexadecimal value, such as AABBCC, into AA, BB, CC and use string.char () sequentially for all of my decimal values ​​to complete the job.

Is there a built-in function that allows me to write such values ​​directly without converting them first? I used escape characters like "0xAA" and "\ xAA", but that didn't work.

Edit: Let me give you an example. I look at the test file in a hex editor:

00000000 00 00 00 00 00 00 ...... 

And I want to write him as follows with the string "AABBCC":

 00000000 AA BB CC 00 00 00 ...... 

What I get with escape characters:

 00000000 41 41 42 42 43 43 AABBCC 
+6
source share
3 answers

I use the following functions to convert between a hexadecimal 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! 
+23
source

So you have a line like this:

 value = 'AABBCC' 

And you want to print it (or include it in a string), how is it?

 '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 

Please note that it leaves untouched any characters that cannot be interpreted as hex.

+2
source

There is such a function because it is easy to write.

 function writeHex(str,fh) for byte in str:gmatch'%x%x' do fh:write(string.char(tonumber(byte,16))) end end 

It simply writes the values ​​to the file pointed to by the file descriptor fh.

+2
source

Source: https://habr.com/ru/post/907625/


All Articles