Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python read binary file byte by byte

Tags:

python

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!

like image 494
glezo Avatar asked Apr 20 '26 23:04

glezo


1 Answers

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
like image 188
slashdottir Avatar answered May 01 '26 20:05

slashdottir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!