Interpret string 0x as hex in Python

I am adding a few hex bytes to packet = []and I want to return these hex bytes in the form 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 convert ('2a', '19', '00', '00')to packetto get (0x2a, 0x19, 0x0, 0x0)in packHex? I need real hex data, not strings that look like hex data.

I am collecting a package to send to pcap, pcap_sendpacket(fp,packet,len(data))where it packetshould be a hexadecimal list or a tuple for me, maybe it can be done in the decimal system, I haven’t tried it, I prefer hex, Thanks for your answer.

packetPcap[:len(data)] = packHex

It is decided:

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

If output in hexadecimal format is necessary, this command can be used: print ",".join(map(hex, packHex))

+3
3

list int 16 ( "%x"%value, hex)? (, - ), int , 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
+3

" ", . , , .

, :

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

:

tuple(int(x, 16) for x in packet)
+5

, list = ["2a", "19", "00", "00"]

list = [hex(int(i, 16)) for i in vals]

.

>>>['0x2a', '0x19', '0x0', '0x0']
-1

Source: https://habr.com/ru/post/1772118/


All Articles