3

I'm trying to convert and write string data into the file as bytes.

I have already tried something to, but instead of seeing 00 inside hexdump, im seeing 0x30 inside file which is hexadecimal value for character 0.

Here is what I wrote:

local data = "000000010000000100000004000000080000000100000000"
for i=1,#data,2 do
  file:write(tonumber(data:sub(i,i+1)))
end
io.close(file)

When I do hexdump of the file I'm getting this:

0000000 30 30 30 31 30 30 30 31 30 30 30 34 30 30 30 38  
0000010 30 30 30 31 30 30 30 30  
0000018

Expected is:

0000000 00 00 00 01 00 00 00 01 00 00 00 04 00 00 00 08  
0000010 00 00 00 01 00 00 00 00  
0000018
1
  • Use file:close() for consistency. Commented Aug 27, 2019 at 14:41

2 Answers 2

3

You want to use string.char in one way:

local data = "000000010000000100000004000000080000000100000000"
for i=1,#data,2 do
  file:write(string.char(tonumber(data:sub(i,i+1), 16)))
end
io.close(file)

or another:

local data = string.char(0,0,0,1,0,0,0,1,0,0,0,4,0,0,0,8,0,0,0,1,0,0,0,0)
file:write(data)
io.close(file)

Note that strings in Lua may contain any bytes you want including null bytes. See Values and Types.

Sign up to request clarification or add additional context in comments.

Comments

1

Hint: Use string.char to convert numbers to bytes:

file:write(string.char(tonumber(data:sub(i,i+1))))

If the strings contains hexadecimal, use tonumber(...,16).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.