[英]python 'long' hex value to decimal
嗨,我想将值十六进制为十进制而没有循环(因为“速度”问题)
ex)
>>> myvalue = "\xff\x80\x17\x90\x12\x44\x55\x99\x90\x12\x80"
>>> int(myvalue)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\xff\x80\x17\x90\x12DU\x99\x90\x12\x80'
>>> ord(myvalue)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 11 found
>>>
有人帮忙吗?
您的数字似乎是作为二进制数据给出的整数。 在Python 3.2中,您可以使用int.from_bytes()
将其转换为Python整数:
>>> myvalue = b"\xff\x80\x17\x90\x12\x44\x55\x99\x90\x12\x80"
>>> int.from_bytes(myvalue, "big")
308880981568086674938794624
我可以为Python 2.x提出的最佳解决方案是
>>> myvalue = "\xff\x80\x17\x90\x12\x44\x55\x99\x90\x12\x80"
>>> int(myvalue.encode("hex"), 16)
308880981568086674938794624L
由于这不涉及Python循环,因此应该很快。
struct
模块很可能不会使用循环:
import struct
valuesTuple = struct.unpack ('L', myValue[:4])
当然,这将数值限制为基本数据类型(int,long int等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.