[英]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 = []
,我希望以0x__
的形式返回这些十六进制字节作为十六进制数据。
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
? 如何在
packet
转换('2a', '19', '00', '00')
以获取packHex
(0x2a, 0x19, 0x0, 0x0)
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. 我正在组装一个要通过
pcap
发送的数据包, pcap_sendpacket(fp,packet,len(data))
,其中packet
应该是十六进制列表或者元组,也许它可以用十进制表示,没试过,我更喜欢十六进制。 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))
如果需要以十六进制输出,可以使用此命令:
print ",".join(map(hex, packHex))
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)
Why don't you just build a list
of int
s and just print them out in base 16 (either by using "%x"%value
or hex
) instead? 为什么不直接构建一个
int
list
并将它们打印在基数16(通过使用"%x"%value
或hex
)代替? If the values are given to you in this form (eg from some other source), you can use int
with the optional second parameter to turn this into an int
. 如果值(从其他来源例如)给你以这种形式,可以使用
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
Say you have a list = ["2a", "19", "00", "00"]
假设你有一个
list = ["2a", "19", "00", "00"]
For me I use list = [hex(int(i, 16)) for i in vals]
对我来说
list = [hex(int(i, 16)) for i in vals]
使用list = [hex(int(i, 16)) for i in vals]
It then returns a new list with hex type of all the elements. 然后它返回一个包含所有元素的十六进制类型的新列表。
>>>['0x2a', '0x19', '0x0', '0x0']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.