2

I read this question, and I checked it myself.

I use the following snippet:

f = io.open("file.file", "wb")
f:write(1.34)
f:close()

This creates the file, into which 1.34 is written. This is same as : 00110001 00101110 00110011 00110100 , that is binary codes for the digit 1, the decinal point, then 3 and finally 4.

However, I would like to have printed 00111111 10101100 11001100 11001101, which is a true float representation. How do I do so?

11
  • 1
    Use hexafloats: f:write(('%.13a'):format(1.34)) Commented Jul 23, 2014 at 17:48
  • I'm not sure I understand the question entirely but you might need something like lpack (or similar) for this. Commented Jul 23, 2014 at 17:50
  • @EgorSkriptunoff's answer is not valid for lua 5.1, but is valid in lua 5.2. (I have no idea if it is correct.) Commented Jul 23, 2014 at 17:51
  • BTW, you can simply store 17 decimal digits of the number f:write(('%.17g'):format(1.34)) to avoid any rounding errors and receive exactly the same number with tonumber. This works in Lua 5.1 Commented Jul 23, 2014 at 18:23
  • @EgorSkriptunoff and the corresponding read command would be f:read(('%.17g'):format(1.34)) ? Commented Jul 23, 2014 at 19:36

1 Answer 1

2

You may need to convert it to binary representation, using something similar to this answer. This discussion on serialization of lua numbers may also be useful.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.