Convert hex string to integer in Python
Without the 0x
prefix, you need to specify the base explicitly, otherwise there's no way to tell:
x = int("deadbeef", 16)
With the 0x
prefix, Python can distinguish hex and decimal automatically:
>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
(You must specify 0
as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, int()
will assume base-10.)
Convert hex-string to integer with python
Not only that is a string, but it is in little endian order - meanng that just removing the spaces, and using int(xx, 16)
call will work. Neither does it have the actual byte values as 4 arbitrary 0-255 numbers (in which case struct.unpack would work).
I think a nice approach is to swap the components back into "human readable" order, and use the int call - thus:
number = int("".join("6c 02 00 00".split()[::-1]), 16)
What happens there: the first part of th expession is the split
- it breaks the string at the spaces, and provides a list with four strings, two digits in each. The [::-1] special slice goes next - it means roughly "provide me a subset of elements from the former sequence, starting at the edges, and going back 1 element at a time" - which is a common Python idiom to reverse any sequence.
This reversed sequence is used in the call to "".join(...)
- which basically uses the empty string as a concatenator to every element on the sequence - the result of the this call is "0000026c". With this value, we just call Python's int
class which accepts a secondary optional paramter denoting the base that should be used to interpret the number denoted in the first argument.
>>> int("".join("6c 02 00 00".split()[::-1]), 16)
620
Another option, is to cummulatively add the conversion of each 2 digits, properly shifted to their weight according to their position - this can also be done in a single expression using reduce
, though a 4 line Python for
loop would be more readable:
>>> from functools import reduce #not needed in Python2.x
>>> reduce(lambda x, y: x + (int(y[1], 16)<<(8 * y[0]) ), enumerate("6c 02 00 00".split()), 0)
620
update The OP just said he does not actually have the "spaces" in the string - in that case, one can use just abotu the same methods, but taking each two digits instead of the split()
call:
reduce(lambda x, y: x + (int(y[1], 16)<<(8 * y[0]//2) ), ((i, a[i:i+2]) for i in range(0, len(a), 2)) , 0)
(where a
is the variable with your digits, of course) -
Or, convert it to an actual 4 byte number in memory, usign the hex codec, and unpack the number with struct - this may be more semantic correct for your code:
import codecs
import struct
struct.unpack("<I", codecs.decode("6c020000", "hex") )[0]
So the approach here is to pass each 2 digits to an actual byte in memory in a bytes object returned by the codecs.decode
call, and struct to read the 4 bytes in the buffer as a single 32bit integer.
Python convert Hex string to Signed Integer
You could do a 64-bit version of this, for example:
def signed_int(h):
x = int(h, 16)
if x > 0x7FFFFFFFFFFFFFFF:
x -= 0x10000000000000000
return x
print(signed_int('0xb69958096aff3148'))
Output
-5289099489896877752
How to convert hex str into int array
You could range(..)
over substrings of length 2:
c = '8db6796fee32785e366f710df10cc'
c2=[int(c[i:i+2],16) for i in range(0,len(c),2)]
So i
iterates of the string with steps of 2 and you take a substring of length 2 from i
to i+2
(exclusive) with c[i:i+2]
. These you convert by taking int(..,16)
.
For your sample input it generates:
>>> c='8db6796fee32785e366f710df10cc'
>>> [int(c[i:i+2],16) for i in range(0,len(c),2)]
[141, 182, 121, 111, 238, 50, 120, 94, 54, 111, 113, 13, 241, 12, 12]
The last element is 12
because the length of your string is odd, so it takes c
as the last element to parse.
Python: Convert hex string to int and back
def str_to_int(s):
i = int(s, 16)
if i >= 2**23:
i -= 2**24
return i
def int_to_str(i):
return '%06x'%((i+2**24)%2**24)
Test results:
In [36]: str_to_int('012345')
Out[36]: 74565
In [37]: str_to_int('fedcba')
Out[37]: -74566
In [38]: int_to_str(74565)
Out[38]: '012345'
In [39]: int_to_str(-74566)
Out[39]: 'fedcba'
Reference: Hex string to signed int in Python 3.2?
How to convert a hex string to an integer?
The value you have is a byte string, not hex. You can encode it to hex then interpret that as a base 16 number. Assuming the return value is meant to be interpreted as one number, and knowing nothing about the format, such as little endian vs big endian, and assuming the \xoo
was a typo for \x00
.
from binascii import hexlify
data = serial.readline()
hex = hexlify(data)
num = int(hex, 16)
print(num)
How to convert a hex string to hex number
Try this:
hex_str = "0xAD4"
hex_int = int(hex_str, 16)
new_int = hex_int + 0x200
print hex(new_int)
If you don't like the 0x
in the beginning, replace the last line with
print hex(new_int)[2:]
Python hexadecimal string to integer conversion error
Python 3 has no limit on it's integer values.
So you can use int(hex_string, 16) to convert even large strings to an integer value.
s = '14fdbc5ade9e3d4097f421fe7b4b54ad05883d589c3b3f6648b5e0ea2b64b359158087b793b859a4c51af0fd8c1edb7a92b8d5843c1a2d659929357c7e1869784435d6dcfd8d29b619194333b38655493eb4eb3deeffbf339e91c7c0f6113b4bb6672f49'
s_int = int(s, 16)
print(s_int)
Result
546755182137531943293891170863886409257177002102958031106970218913938945216495276608761007929774380907079475078176395384371438944791022503587328767282546555465705414556027853888426781796298321719051075009856267471199860627126795651319803721
Convert hex string to usably hex
You have a string in input. You can convert it to an integer using int
and a base.
>>> a = "0xbffffe43"
>>> import struct
>>> out = struct.pack("<I",int(a,16))
>>> out
b'C\xfe\xff\xbf'
The b
prefix is there because solution was tested with python 3. But it works as python 2 as well.
C
is printed like this because python interprets printable characters. But
>>> b'C\xfe\xff\xbf' == b'\x43\xfe\xff\xbf'
True
see:
- Convert hex string to int in Python
- Convert a Python int into a big-endian string of bytes
Related Topics
Why Does List.Append Evaluate to False in a Boolean Context
C Function Called from Python Via Ctypes Returns Incorrect Value
Combine Two Columns of Text in Pandas Dataframe
How to Implement Nested Dictionaries
Pandas Groupby With Delimiter Join
Writing a List to a File With Python, With Newlines
How to Get Json to Load into an Ordereddict
How to Set Environment Variables in Python
About the Changing Id of an Immutable String
How to Stop More Than 1 Bullet Firing At Once
How to Measure Elapsed Time in Python
Split String With Multiple Delimiters in Python
Use a List of Values to Select Rows from a Pandas Dataframe
Pip Install from Git Repo Branch