160

I'm currently working on an encryption/decryption program and I need to be able to convert bytes to an integer. I know that:

bytes([3]) = b'\x03'

Yet I cannot find out how to do the inverse. What am I doing terribly wrong?

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Vladimir Shevyakov
  • 2,511
  • 4
  • 19
  • 40
  • 3
    There is also the `struct` module if you want to convert multiple variables at once. – tdelaney Nov 30 '15 at 23:53
  • Possible duplicate of [Reading integers from binary file in Python](https://stackoverflow.com/q/1163459/608639), [How to convert a string of bytes into an int in Python](https://stackoverflow.com/q/444591/608639), etc. – jww Dec 23 '18 at 12:41
  • 2
    inverse: `b'\x03'[0]` – djvg Dec 22 '20 at 18:01
  • If you have a bytes object `var = b'abc'`, then `var[0]` would return `97` and `var[1]` `98`, and so on. – Have a nice day Apr 29 '21 at 17:11

8 Answers8

263

Assuming you're on at least 3.2, there's a built in for this:

int.from_bytes( bytes, byteorder, *, signed=False )

...

The argument bytes must either be a bytes-like object or an iterable producing bytes.

The byteorder argument determines the byte order used to represent the integer. If byteorder is "big", the most significant byte is at the beginning of the byte array. If byteorder is "little", the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value.

The signed argument indicates whether two’s complement is used to represent the integer.

## Examples:
int.from_bytes(b'\x00\x01', "big")                         # 1
int.from_bytes(b'\x00\x01', "little")                      # 256

int.from_bytes(b'\x00\x10', byteorder='little')            # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True)  #-1024
martineau
  • 119,623
  • 25
  • 170
  • 301
Peter DeGlopper
  • 36,326
  • 7
  • 90
  • 83
  • 3
    Thanks. Is there a difference between `int.from_bytes` and `ord(b'\x03')` for single bytes/chars? – Bill Jun 09 '19 at 19:39
  • 5
    The only difference I can think of is that `int.from_bytes` can interpret the byte as a signed integer if you tell it to - `int.from_bytes(b'\xe4', "big", signed=True)` returns -28, while `ord()` or `int.from_bytes` in unsigned mode returns 228. – Peter DeGlopper Jun 10 '19 at 03:50
  • use `sys.byteorder` to pass the byte order while calling. – Krishna Oza Jul 26 '21 at 13:41
  • 3
    @KrishnaOza - that depends. If you're converting bytes that were encoded on a remote system, say because you're receiving them over a network connection, there's no guarantee that the remote system's native byte order matches yours. This has been a significant historical problem. – Peter DeGlopper Jul 26 '21 at 14:39
21

Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.

>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist)       # b'@\x04\x1a\xa3\xff'

>>> for b in bytelist:
...    print(b)                     # 64  4  26  163  255

>>> [b for b in bytelist]           # [64, 4, 26, 163, 255]

>>> bytelist[2]                     # 26 
OutstandingBill
  • 2,614
  • 26
  • 38
Ronald
  • 2,930
  • 2
  • 7
  • 18
6

list() can be used to convert bytes to int (works in Python 3.7):

list(b'\x03\x04\x05')
[3, 4, 5]
Dmitriy Work
  • 773
  • 10
  • 17
2
int.from_bytes( bytes, byteorder, *, signed=False )

doesn't work with me I used function from this website, it works well

https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python

def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result

def int_to_bytes(value, length):
    result = []
    for i in range(0, length):
        result.append(value >> (i * 8) & 0xff)
    result.reverse()
    return result
1

In case of working with buffered data I found this useful:

int.from_bytes([buf[0],buf[1],buf[2],buf[3]], "big")

Assuming that all elements in buf are 8-bit long.

Peter Hirt
  • 51
  • 4
1

convert bytes to bit string

format(int.from_bytes(open('file','rb').read()),'b')
-1

An old question that I stumbled upon while looking for an existing solution. Rolled my own and thought I'd share because it allows you to create a 32-bit integer from a list of bytes, specifying an offset.

def bytes_to_int(bList, offset):
    r = 0
    for i in range(4):
        d = 32 - ((i + 1) * 8)
        r += bList[offset + i] << d
    return r
-1
#convert bytes to int 
    def bytes_to_int(value):
        return int.from_bytes(bytearray(value), 'little')

    bytes_to_int(b'\xa231')