1

I'd like to know how to convert strings in Python to their corresponding integer values, like so:

>>>print WhateverFunctionDoesThis('\x41\x42')

>>>16706

I've searched around but haven't been able to find an easy way to do this.

Thank you.

3 Answers 3

7
>>> import struct
>>> struct.unpack(">h",'\x41\x42')
(16706,)
>>> struct.unpack(">h",'\x41\x42')[0]
16706

For other format chars see the documentation

Sign up to request clarification or add additional context in comments.

Comments

0

If '\x41\x42' is 16-based num, like AB. You can use string to convert it.

import string

agaga = '\x41\x42'
string.atoi(agaga, 16)
>>> 171

Sorry if i got you wrong...

1 Comment

you're right, '\x41\x42' == 'AB' and in some universe Jason would ask for 0xAB result, instead of 0x4142
0

ugly way:

>>> s = '\x41\x42'
>>> sum([ord(x)*256**(len(s)-i-1) for i,x in enumerate(s)])
16706

or

>>> sum([ord(x)*256**i for i,x in enumerate(reversed(s))])

1 Comment

I think left shift is nicer than exponents sum([ord(x)<<(i*8) for i,x in enumerate(reversed(s))])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.