0

hi i want to hex value to decimal without loop(because 'speed' problem)

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

anyone helps ?

osmund sadler
  • 1,021
  • 2
  • 15
  • 27

2 Answers2

4

Your number seems to be an integer given as binary data. In Python 3.2, you can convert it to a Python integer with int.from_bytes():

>>> myvalue = b"\xff\x80\x17\x90\x12\x44\x55\x99\x90\x12\x80"
>>> int.from_bytes(myvalue, "big")
308880981568086674938794624

The best solution I can come up with for Python 2.x is

>>> myvalue = "\xff\x80\x17\x90\x12\x44\x55\x99\x90\x12\x80"
>>> int(myvalue.encode("hex"), 16)
308880981568086674938794624L

Since this does not involve a Python loop, it should be pretty fast, though.

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
0

The struct module will most likely not use a loop:

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

Of course this limits the numerical values to basic data types (int, long int, etc.)

wroniasty
  • 7,884
  • 2
  • 32
  • 24