Smith
Smith

Reputation: 3053

Arranging hexadecimal horizontally

I have a binary file that need to be showed in hexadecimal. The code as follows :

file=open('myfile.chn','rb')  
for x in file:     
    i=0
    while i<len(x):
        print ("%0.2X"%(x[i]))
        i=i+1
        if (i>=10): 
            i=0
            break
file.close()

and the result i get as follows :

FF  
FF  
01  
00  
01  
00  
35  
36  
49  
EC      
.   
.   
. 

Which part of the code that i need to change in order to show the result just as follows?

FF FF 01 00 01   
00 35 36 49 EC  
.  
.  

(with a space between each byte)

Upvotes: 1

Views: 189

Answers (3)

Thomas Jung
Thomas Jung

Reputation: 33092

As you take only 10 elements I'd use:

print(" ".join("%0.2X" % s for s in x[:10]))

or if you want to include the whole line:

print(" ".join("%0.2X" % s for s in x))

There is still a bug from your initial version. Your input is read as one string per line. The type conversion "%0.2X" fails ("%s" works). I think you cannot read binary file per line. \n is just another byte and cannot be interpreted as newline.

When you have a sequence of int values you can create partitions of n elements with the group method. The group method is in the itertools recipies.

from itertools import zip_longest

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=None, *args)

width=10
x = range(1,99)
for group in grouper(width, x):
    print((" ".join("%0.2X" % s for s in group if s)))

Output:

01 02 03 04 05 06 07 08 09 0A
0B 0C 0D 0E 0F 10 11 12 13 14
15 16 17 18 19 1A 1B 1C 1D 1E
1F 20 21 22 23 24 25 26 27 28
29 2A 2B 2C 2D 2E 2F 30 31 32
33 34 35 36 37 38 39 3A 3B 3C
3D 3E 3F 40 41 42 43 44 45 46
47 48 49 4A 4B 4C 4D 4E 4F 50
51 52 53 54 55 56 57 58 59 5A
5B 5C 5D 5E 5F 60 61 62

To bytes_from_file reads bytes as generator :

def bytes_from_file(name):
    with open(name, 'rb') as fp:
        def read1(): return fp.read(1)
        for bytes in iter(read1, b""):
            for byte in bytes:
                yield byte

x = bytes_from_file('out.fmt') #replaces x = range(1,99)

Upvotes: 3

Ulf Rompe
Ulf Rompe

Reputation: 929

file=open('myfile.chn','rb')  
for x in file:

       char=0
       i=0
       while i<len(x):
           print ("%0.2X "%(x[i])),
           char += 1
           if char == 5:
               char=0
               print ''
           i=i+1
           if (i>=10): 
               i=0
               break
file.close()

Upvotes: 0

Jeethu
Jeethu

Reputation: 429

This should do it.

for i, x in enumerate(file):
    print ("%0.2X" % (x)),
    if i > 0 and i % 5 == 0:
        print

Upvotes: 1

Related Questions