DEV Community

Mansour Moufid
Mansour Moufid

Posted on

Quick bytes to integer (or other type) conversion in Python

Sometimes you have a bytes object but what you really want is an integer.

For example, I want the unsigned 32-bit integer represented by b'1234'. I can do the conversion with struct.unpack:

>>> struct.unpack('I', b'1234')
(875770417,)
Enter fullscreen mode Exit fullscreen mode

or using the from_buffer/from_buffer_copy functions of the ctypes module:

>>> ctypes.c_uint32.from_buffer_copy(b'1234')
c_uint(875770417)
Enter fullscreen mode Exit fullscreen mode

This is usually used for compound types (also called composite data types, i.e. types that are defined in terms of primitive data types, like a C structure), but still useful for simple things like integers.

Top comments (0)