Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interpret 0x string as hex in Python

I'm appending some hex bytes into a packet = [] and I want to return these hex bytes in the form of 0x__ as hex data.

packet.append("2a")
packet.append("19")
packet.append("00")
packet.append("00")

packHex = []

for i in packet:
    packHex.append("0x"+i) #this is wrong

return packHex

How do I go about converting ('2a', '19', '00', '00') in packet to get (0x2a, 0x19, 0x0, 0x0) in packHex? I need real hex data, not strings that look like hex data.

I'm assembling a packet to be sent over pcap, pcap_sendpacket(fp,packet,len(data)) where packet should be a hexadecimal list or tuple for me, maybe it can be done in decimal, haven't tried, I prefer hex. Thank you for your answer.

packetPcap[:len(data)] = packHex

Solved:

for i in packet: packHex.append(int(i,16))

If output in hex needed, this command can be used: print ",".join(map(hex, packHex))

like image 416
soulseekah Avatar asked Jan 21 '23 04:01

soulseekah


2 Answers

You don't really want 'hex data', you want integers. Hexadecimal notation only makes sense when you have numbers represented as strings.

To solve your problem use a list comprehension:

[int(x, 16) for x in packet]

Or to get the result as a tuple:

tuple(int(x, 16) for x in packet)
like image 177
Mark Byers Avatar answered Jan 29 '23 11:01

Mark Byers


Why don't you just build a list of ints and just print them out in base 16 (either by using "%x"%value or hex) instead? If the values are given to you in this form (e.g. from some other source), you can use int with the optional second parameter to turn this into an int.

>>> int('0x'+'2a',16)
42
>>> packet=["2a","19","00","00"]
>>> packet=[int(p,16) for p in packet]
>>> packet
[42, 25, 0, 0]
>>> print ", ".join(map(hex,packet))
0x2a, 0x19, 0x0, 0x0
like image 24
MAK Avatar answered Jan 29 '23 11:01

MAK