0

嗨,我想在没有循环的情况下将十六进制值转换为十进制(因为“速度”问题)

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
>>>

有人帮忙吗?

4

2 回答 2

4

您的数字似乎是作为二进制数据给出的整数。在 Python 3.2 中,您可以使用以下命令将其转换为 Python 整数int.from_bytes()

>>> 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 循环,因此它应该非常快。

于 2012-06-03T14:33:30.410 回答
0

struct模块很可能不会使用循环:

import struct
valuesTuple = struct.unpack ('L', myValue[:4])

当然,这将数值限制为基本数据类型(int、long int 等)

于 2012-06-03T14:48:28.063 回答