How to create a fixed size (unsigned) integer in python?

后端 未结 4 956
渐次进展
渐次进展 2021-01-13 02:39

I want to create a fixed size integer in python, for example 4 bytes. Coming from a C background, I expected that all the primitive types will occupy a constant space in mem

4条回答
  •  庸人自扰
    2021-01-13 03:21

    You can use struct.pack with the I modifier (unsigned int). This function will warn when the integer does not fit in four bytes:

    >>> from struct import *
    >>> pack('I', 1000)
    '\xe8\x03\x00\x00'
    >>> pack('I', 10000000)
    '\x80\x96\x98\x00'
    >>> pack('I', 1000000000000000)
    sys:1: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295
    '\x00\x80\xc6\xa4'
    

    You can also specify endianness.

提交回复
热议问题