Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a hexadecimal string into chunks in Python

Tags:

python

string

hex

I have this part of code in Python:

for line in response.body.split("\n"):
    if line != "": 
        opg = int(line.split(" ")[2])
        opc = int(line.split(" ")[3])
        value = line.split(" ")[5]
        if command == 'IDENTIFY':
            if opg==opcodegroupr and opc==opcoder:
                print line
                ret['success'] = "IDENTIFY: The value is %s " % (value)
                self.write(tornado.escape.json_encode(ret))
                self.finish()

Variable 'line' is made in this way:

1363005087 2459546910990453036 151 88 4 0x15000000

Every field is an integer, but not the last field. The last field is an hex number.

I would take this hex number and after split byte per byte. For example I would that 0x15000000 was splitted in 15 00 00 00.

How can I do? I tried with value.encode("hex") but dowsn't work fine... value is a string? I don't know how consider this variable..

like image 785
sharkbait Avatar asked Apr 11 '26 09:04

sharkbait


1 Answers

If the hexadecimal value is already text, you don't need to do any more conversion:

>>> text = "0x15000000"
>>> text = text[2:]  # remove literal type prefix
>>> text = text.zfill(len(text) + len(text) % 2)  # pad with zeros for even digits
>>> ' '.join(text[i: i+2] for i in range(0, len(text), 2))  # split into 2-digit chunks
'15 00 00 00'

(edited per @tobias-k's suggestion about zero-padding)

like image 75
Jace Browning Avatar answered Apr 12 '26 23:04

Jace Browning



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!