This might seem pretty stupid, but I'm a complete newbie in python.
So, I have a binary file that starts by
ff d8 ff e0 00 10 4a
(as seen both through Hex Editor Neo and a java program)
yet, when I tried to read it with python by
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
It seems that it goes wrong whenever the first 0x00 is readen.
what am I doing wrong? Thank u!
asked May 18, 2017 at 22:12
glezo
8983 gold badges13 silver badges29 bronze badges
2 Answers 2
I think the issue is you are trying to dereference current_byte as though it were an array, but it is simply 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 the output:
0xff 0xd8 0xff 0xe0 0x0 0x10 0x4a
answered Jun 13, 2017 at 21:39
slashdottir
8,7287 gold badges62 silver badges77 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
import binascii
with open(absolutePathInput, "rb") as f:
buff = f.read()
line = binascii.hexlify(buff)
hex_string = [line[i:i+2] for i in range(0, len(line), 2)]
simple and violent
Comments
lang-py
0instead of00? (It should be printing0xin front of all these hex representations, and it should be printing them on separate lines; it looks like you edited the output. Please don't do that.)