Python read binary byte by byte
This may sound pretty silly, but I am a complete newbie to python.
So, I have a binary starting with
ff d8 ff e0 00 10 4a
(as shown both via Hex Editor Neo and in java program)
but when i tried to read it using python
with open(absolutePathInput, "rb") as f:
while True:
current_byte = f.read(1)
if(not current_byte):
break
print(hex(current_byte[0]))
I get
ff d8 ff e0 0 10 31
This seems to be going wrong when the first 0x00 is read.
what am I doing wrong? Thank u!
+3
source to share
2 answers
I think the problem is that you are trying to play out current_byte as if it were an array, but it is just a byte
def test_write_bin(self):
fname = 'test.bin'
f = open(fname, 'wb')
# ff d8 ff e0 00 10 4a
f.write(bytearray([255, 216, 255, 224, 0, 16, 74]))
f.close()
with open(fname, "rb") as f2:
while True:
current_byte = f2.read(1)
if (not current_byte):
break
val = ord(current_byte)
print hex(val),
print
This program produces output:
0xff 0xd8 0xff 0xe0 0x0 0x10 0x4a
+1
source to share