pythonhexbinascii

I want to read the hexadecimal number of a binary file sequentially by 6 bytes


import binascii
import sys
from os.path import getsize

target = './'+sys.argv[1]

with open(target,'rb+') as f:
    file_size = getsize(target)
    string1 = f.read(6)
    
    print("Size : %d"%file_size)
    print (binascii.b2a_hex(string1))

I have a file that is 1220 bytes in size. ignore the first 20 bytes I want to output 6 bytes from the 21st byte.

for example,
There is hex data of

00 00 00 00 00 ... 00 00 00 ( 20bytes 0x00 ) AA BB CC DD EE FF
GG HH II JJ KK LL
MM ...

My expected Output :
AA BB CC DD EE FF
GG HH II JJ KK LL
MM.... .. .. I want to load and output 6 bytes one by one as shown.

I wrote code to get the file size for this. But I can't quite figure out what to do after that. So I ask for help.


Solution

  • As of now, your code reads the first 6 bytes. To skip 20 bytes before the read you can use the seek() method [1]. To display the hexadecimal values seperated by a space you can use the bytes.hex function [2]. Putting all together you could go with something like:

    import binascii
    import sys
    from os.path import getsize
    
    target = './'+sys.argv[1]
    
    with open(target,'rb+') as f:
        file_size = getsize(target)
        
        # read 6 bytes from position 20
        f.seek(20)
        string1 = f.read(6)
    
        print("Size : %d"%file_size)
        print (string1.hex(' ',1))