This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mansour Moufid
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,)
or using the from_buffer
/from_buffer_copy
functions of the ctypes
module:
>>> ctypes.c_uint32.from_buffer_copy(b'1234')
c_uint(875770417)
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.
This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Mansour Moufid

Mansour Moufid | Sciencx (2022-12-20T00:33:35+00:00) Quick bytes to integer (or other type) conversion in Python. Retrieved from https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.