Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua: writing hexadecimal values as a binary file

Tags:

hex

lua

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
like image 716
Zerobinary99 Avatar asked Feb 04 '12 00:02

Zerobinary99


3 Answers

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!
like image 124
Michal Kottman Avatar answered Nov 08 '22 21:11

Michal Kottman


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.

like image 24
John Zwinck Avatar answered Nov 08 '22 22:11

John Zwinck


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.

like image 1
jpjacobs Avatar answered Nov 08 '22 23:11

jpjacobs