I'm writing a code meant to read a binary file and print the hex representation of its data as a csv, using NULL values as a separator. When looking at a file in a binary/hex viewer, it shows me this sequence as part of the file:
41 73 73 65 6d 62 6c 79 c8 2d 01 00 04 00 00 00 07 00 00 00 00
However, reading the file with this part of code:
with open(file_in, "rb") as f:
while (byte := f.read(1)):
h_value = hex(ord(byte))
h_value = ("0" + h_value[2:])[-2:]
#print(byte)
#print(h_value)
if h_value != '00':
data_read.append(h_value)
else:
data_read.append(h_value)
if data_read:
with open(file_out, 'a', newline = '') as c:
w = csv.writer(c)
w.writerow(data_read)
data_read = []
Gives me this for that section instead:
41,73,73,65,6d,62,6c,79,c3,88,2d,01,20,04,20,20,20,07,20,20,20,20
Which is relevant, because there are actual "20" values elsewhere in the file as data. Using the "print(byte)" and "print(h_value)" return b' '
and 20
respectively, which makes me think that it's Python reading the file wrong, not just the output being converted. Is there anything I can do to preserve these NULL values through the process?
Edit 1: Additional info, this is running Python 3.8.2 using IDLE. No idea if the compiler would make a difference for this, but I'm going to see if Visual Studio gives me different results. The binary viewer is simply named Binary Viewer, version 6.17.