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,)

o…


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


Print Share Comment Cite Upload Translate Updates
APA

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/

MLA
" » Quick bytes to integer (or other type) conversion in Python." Mansour Moufid | Sciencx - Tuesday December 20, 2022, https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/
HARVARD
Mansour Moufid | Sciencx Tuesday December 20, 2022 » Quick bytes to integer (or other type) conversion in Python., viewed ,<https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/>
VANCOUVER
Mansour Moufid | Sciencx - » Quick bytes to integer (or other type) conversion in Python. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/
CHICAGO
" » Quick bytes to integer (or other type) conversion in Python." Mansour Moufid | Sciencx - Accessed . https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/
IEEE
" » Quick bytes to integer (or other type) conversion in Python." Mansour Moufid | Sciencx [Online]. Available: https://www.scien.cx/2022/12/20/quick-bytes-to-integer-or-other-type-conversion-in-python/. [Accessed: ]
rf:citation
» Quick bytes to integer (or other type) conversion in Python | Mansour Moufid | Sciencx | 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.

You must be logged in to translate posts. Please log in or register.