4

I am trying to create a bunch of binary files that contain corresponding hex values

for i in range(2**8):
    file = open("test" + str(i) + ".bin", "wb")
    file.write(hex(i))
    file.close()

Unfortunately it appears that a text representation of my counter converted to hex is being written to the files instead of the actual hex values. Can someone please correct this code? I'm sure the problem is with hex(i)

3
  • 2
    Well, yes... hex(x) docs specifically say that it returns a string. docs.python.org/3/library/functions.html#hex But hex is a representation: do you want to write the binary representation of that hex string? Or the binary representation of i? Commented Jan 24, 2013 at 3:03
  • I suppose you want to write the binary value of i instead of literal value of i to file? Commented Jan 24, 2013 at 3:04
  • 2
    You will want to use struct.pack Commented Jan 24, 2013 at 3:04

1 Answer 1

5

If you want the value to be written in binary, use chr() to create the character from i:

for i in range(2**8):
    with open("test" + str(i) + ".bin", "wb") as f:
        f.write(chr(i))
Sign up to request clarification or add additional context in comments.

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.