chunk of data into fixed lengths chunks and then add a space and again add them all as a string

52 views Asked by At

I have got hex values as a85b080040010000. I want it to be as a8 5b 08 00 40 01 00 00. I have done it by using below code. But I have to work with very large data. So I want computed time to be very low.

import binascii
import re

filename = 'calc.exe'
with open(filename, 'rb') as f:
    content = f.readline()

text = binascii.hexlify(content)
text1 = binascii.unhexlify(text)
length1 = 32
length2 = 16

list = re.findall('.{%d}' % length1, text)
list1 = re.findall('.{%d}' % length2, text1)

d = []
for i in range (0, len(list), 1):
    temp = ""
    l = re.findall('.{%d}' % length2, list[i])

    s = l[0]
    t = iter(s)
    temp += str(' '.join(a+b for a,b in zip(t, t)))

    temp += "  "

    s = l[1]
    t = iter(s)
    temp += str(' '.join(a+b for a,b in zip(t, t)))
    temp += "  | " + list1[i]
    print temp
1

There are 1 answers

5
vks On BEST ANSWER

You can simply do

x="a85b080040010000"
print re.sub(r"(.{2})",r"\1 ",x)

or

x="a85b080040010000"

print " ".join([i for i in re.split(r"(.{2})",x) if i])