0

こんにちは私はループなしで値を10進数に16進数にしたい(「速度」の問題のため)

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 に答える