int('\x23') != 0x23 (a.k.a convert char to integer of its byte representation)

Boris Dušek boris.dusek at gmail.com
Sat Sep 15 07:55:28 EDT 2007


Hi,

I am looking for the best way to convert a string of length 1 (= 1
character as string) to integer that has the same value as numeric
representation of that character. Background: I am writing functions
abstracting endianness, e.g. converting a string of length 4 to the
appropriate integer value (e.g. '\x01\x00\x00\x00' = 2**24 for big
endian memory, 2**0 for little endian memory). For this, I need to
know the numeric value of each byte and sum them according to
endianness.

I thought that something like int('\x01') might work, provided the
argument is string of length 1, but that throws an error:

>>> int('\x12')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int():

The code I want to write looks like this:

mem = '\x11\x22\x33\x44'
factor = 1
sum = 0
for byte in mem:
    sum += int(byte) * factor
    factor *= 2**8

Could you please tell me how to achieve what I want in Python? (it
would be straightforward in C)

Thanks for any suggestions,
Boris Dušek




More information about the Python-list mailing list