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

后端 未结 4 957
渐次进展
渐次进展 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:39

    you are missing something here I think

    when you send a character you will be sending 1 byte so even though

    sys.getsizeof('\x05') 
    

    reports larger than 8 you are still only sending a single byte when you send it. the extra overhead is python methods that are attached to EVERYTHING in python, those do not get transmitted

    you complained about getsizeof for the struct pack answer but accepted the c_ushort answer so I figured I would show you this

    >>> sys.getsizeof(struct.pack("I",15))
    28
    >>> sys.getsizeof(c_ushort(15))
    80
    

    however that said both of the answers should do exactly what you want

提交回复
热议问题