Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 20, 2022 12:33 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To