Fixed width integer types (e.g. uint32) in Python

别来无恙 提交于 2019-12-02 04:25:21

问题


Certain mathematical operations, especially on data read from hardware drivers, can depend on fixed width of the data type. Example: bitwise shift. What is the Pythonic way of creating integer variables with fixed width (e.g. uint32, int16 etc.) that would overflow/shift accordingly?


回答1:


I would suggest the fixedint library. The classes in that library are named in the following convention:

[Mutable][U]Int<N>

So for your two examples, the classes would be

#    C++                 Python fixedint
 std::uint32                 UInt32
 std::uint16                 UInt16

This supports things like bit-shifting, etc

>>> a = fixedint.UInt32(14)
>>> a
UInt32(14)
>>> a << 2
UInt32(56)



回答2:


For interfacing with hardware we normally use the struct standard library - specifically struct.pack and struct.unpack not only are fixed widths handled but also endianess issues. See the python 2 or python 3 library manuals.



来源:https://stackoverflow.com/questions/31145143/fixed-width-integer-types-e-g-uint32-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!