Python little endian hex to int

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.

  1. HowTo
  2. Python How-To's
  3. Convert Hex String to Int in Python

Created: December-05, 2020 | Updated: December-10, 2020

  1. Use int() to Convert Hex to Int in Python
  2. Convert Non-Prefixed Hex String to Int in Python
  3. Convert Prefixed Hex String to Int in Python
  4. Convert Little and Big Endian Hex String to Int in Python
  5. Convert Hex to Signed Integer in Python

This tutorial will demonstrate how to convert the hex string to int in Python. It will cover different hex formats like signed, little, and big-endian, 0x annotated hexadecimal, and the default hex string.

Use int() to Convert Hex to Int in Python

The most common and effective way to convert hex into an integer in Python is to use the type-casting function int().

This function accepts two arguments: one mandatory argument, which is the value to be converted, and a second optional argument, which is the base of the number format with the default as 10.

Other number formats are 2 for binary, 8 for octal, and 16 for hexadecimal. If you put 0 as the argument for the base value, it will derive the number format from the value’s prefix. If there isn’t any prefix, it will automatically recognize it as a decimal, 0b for binary, 0o for octal, and 0x for hexadecimal.

Convert Non-Prefixed Hex String to Int in Python

If the hexadecimal string is not prefixed, then specify the base value of the int() function to be 16.

For example:

hex_val = 'beef101'

print(int(hex_val, 16))

Output:

200208641

The result is the decimal or integer conversion of the hex value beef101.

Convert Prefixed Hex String to Int in Python

If the hex string has a prefix 0x, then change the base value argument to 0 to detect the prefix automatically.

You can still pass 16 as the base, but if you’re dealing with multiple values with different number formats, passing 0 is the best approach.

hex_val = '0xdeadcab'

print(int(hex_val, 0))
print(int(hex_val, 16))

Output:

233495723
233495723

Convert Little and Big Endian Hex String to Int in Python

Little endian and big-endia byte orders are two types of ordering systems for hexadecimal. The default order is little-endian, which puts the most significant number in the right-most part of the sequence, while the big-endian does the opposite.

With that in mind, all we have to consider is to convert the big-endian hexadecimal value into a little-endian. Afterward, the usual conversion can now be performed on it.

To convert a big-endian hexadecimal string to a little-endian one, use bytearray.fromhex() and use the function reverse() on the result. Afterward, convert the hexadecimal value back to string and convert it to an integer.

big_endian = 'efbe'

def to_little(val):
  little_hex = bytearray.fromhex(val)
  little_hex.reverse()
  print("Byte array format:", little_hex)

  str_little = ''.join(format(x, '02x') for x in little_hex)

  return str_little

little_endian = to_little(big_endian)

print("Little endian hex:", little_endian)
print("Hex to int:", int(little_endian, 16))

To summarize this code block:

  • Call bytearray.fromhex() to convert the big-endian hex string into a byte array hexadecimal value.
  • Reverse the byte array to convert the big-endian into a little-endian format.
  • Convert the byte array value back into a string hex format in little-endian.
  • Convert the string into an integer using int().

Output:

Byte array format: bytearray(b'\xbe\xef')
Little endian hex: beef
Hex to int: 48879

Convert Hex to Signed Integer in Python

Converting any number format into a signed integer would need an operation called the Two’s Complement, which is a bitwise mathematical operation to compute for signed numbers.

So before we can convert hexadecimal into a signed integer, we would need to define a function that will carry out the Two’s Complement operation.

def twosComplement_hex(hexval):
    bits = 16 # Number of bits in a hexadecimal number format
    val = int(hexval, bits)
    if val & (1 << (bits-1)):
    val -= 1 << bits
    return val

The left-most bit in a binary value is called the signed bit, determining if the integer is positive or negative. This function will reserve that bit as the signed bit and shift the other bits to compensate by using the bitwise left shift operator <<.

Now, moving on to the actual conversion of the hex value to signed int.

hex_val1 = 'ff'
hex_val2 = 'ffff'
hex_val3 = 'aaff'

def twosComplement_hex(hexval):
    bits = 16
    val = int(hexval, bits)
    if val & (1 << (bits-1)):
        val -= 1 << bits
    return val
  
print(twosComplement_hex(hex_val1))
print(twosComplement_hex(hex_val2))
print(twosComplement_hex(hex_val3))

Output:

255
-1
-21761

Now, we’ve achieved converting a hex string into a signed integer.

In summary, we have covered converting different types of hexadecimal formats into signed and unsigned integers. Use int() with the value and base arguments to convert a hex into an unsigned integer.

If the hexadecimal is in a big-endian format, convert it into a little-endian format first using bytearray.fromhex() and reverse().

Lastly, if you need to convert a hex string to a signed integer, then perform the Two’s Complement operation on the hexadecimal value on it to get a signed integer value.

Related Article - Python Hex

  • Convert Binary to Hex in Python
  • Convert HEX to RGB in Python
  • Convert Hex to ASCII in Python
  • String to Hex in Python

    Related Article - Python Integer

  • Convert Binary to Hex in Python
  • Convert HEX to RGB in Python
  • Convert Hex to ASCII in Python
  • String to Hex in Python
  • Python little endian hex to int

    How do you convert hex to int in Python?

    To convert a hexadecimal string to an integer, pass the string as a first argument into Python's built-in int() function. Use base=16 as a second argument of the int() function to specify that the given string is a hex number.

    How do you convert hex to little endian in Python?

    To convert a big-endian hexadecimal string to a little-endian one, use bytearray. fromhex() and use the function reverse() on the result. Afterward, convert the hexadecimal value back to string and convert it to an integer.

    How can I convert a hex string to an integer value?

    To convert a hexadecimal string to a number Use the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

    How do I print a hex value without 0x in Python?

    Use a formatted string literal to get the hex representation of a value without 0x , e.g. result = f'{my_int:x}' . The formatted string literal will format the value in hex without the 0x prefix.