1

I'm trying to read hex values from a binary file. I don't have a problem with extracting a string and converting letters to hex values, but how can I do that with control characters and other non-printable characters? Is there a way of reading the string directly in hex values without the need of converting it?

2 Answers 2

3

Have a look over here:

As a last example, the following program makes a dump of a binary file. Again, the first program argument is the input file name; the output goes to the standard output. The program reads the file in chunks of 10 bytes. For each chunk, it writes the hexadecimal representation of each byte, and then it writes the chunk as text, changing control characters to dots.

local f = assert(io.open(arg[1], "rb"))
local block = 10
while true do
  local bytes = f:read(block)
  if not bytes then break end
  for b in string.gfind(bytes, ".") do
    io.write(string.format("%02X ", string.byte(b)))
  end
  io.write(string.rep("   ", block - string.len(bytes) + 1))
  io.write(string.gsub(bytes, "%c", "."), "\n")
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Excuse my noobishness :)
3

From your question it's not clear what exactly you aim to do, so I'll give 2 approaches.

Either you have a file full with hex values, and read it like this:

s='ABCDEF1234567890'
t={}
for val in s:lower():gmatch'(%x%x)' do
    -- do whatever you want with the data
    t[#t+1]=s:char(val)
end

Or you have a binary file, and you convert it to hex values:

s='kl978331asdfjhvkasdf'
t={s:byte(1,-1)}

1 Comment

Thanks for your reply. I'm actually trying to read hex value of certain offsets in the file. I'm using string.byte now to get the decimal conversion, which is sufficient for my project :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.