Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write ANSI compatible bytes in Python 3 (0x80 and up)?

I am new to python and try to write a script which makes byte 0x00-0xff output to a file.

This is the code i am currently looking at

import sys

filename="binarywriter.txt"
openmode="wb"
charset="utf8"

file=open(filename, openmode)
for x in range(16,256):
    s="0x%.2x=\\x" %x
    s+=hex(x)[2:]
    d=bytes(s, charset).decode("unicode_escape")
    file.write(d.encode(charset))
    file.write("\r\n".encode(charset))
file.close()
sys.stdin.readline()

The thing is that the python script writes all well until byte 0x7f (which is ascii) after this (0x80) it converts all output in utf8 encoding which has 2 bytes. The thing is to avoid this and only write something like this:

...
0x7f
0x80
0x81
...

so i need something like 8bit encoding but after hour of searching there has not been any result for me

there is also a little problem, where numbers <16 return a single hex value which cannot be decoded, but i might find a solution for this

like image 309
syss Avatar asked May 24 '26 05:05

syss


2 Answers

You can use Latin-1 (also known as ISO_8859-1) encoding.

charset="iso-8859-1"

See the screenshot for the proof that every character only needs one byte in the file: Screenshot of hexeditor showing file

like image 96
halex Avatar answered May 26 '26 18:05

halex


If you're after a file of 256 bytes in length that represents 0x00 through 0xFF then you can use:

with open('binary.dat', 'wb') as fout:
    fout.write(bytes(range(256)))
like image 26
Jon Clements Avatar answered May 26 '26 20:05

Jon Clements