An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
December 20, 2022 12:33 am GMT
Original Link: https://dev.to/eliteraspberries/quick-bytes-to-integer-or-other-type-conversion-in-python-27lg
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,)
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.
Original Link: https://dev.to/eliteraspberries/quick-bytes-to-integer-or-other-type-conversion-in-python-27lg
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To