Python:如何从4byte数组中获取4byte大小的整数?

2024-07-04 17:17:59 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我编写的一个简单的Python(版本3.4)代码,从一个4字节的数组中获取一个32位大小的整数(我假设是int类型):

import binascii
import socket   
import struct
import array
import pickle
import ctypes
import numpy
import sys

float_val = 1.0 + 0.005
print(float_val)

packed = struct.pack('f', float_val)
print(len(packed)) 

tempint2 = struct.unpack(">I", packed)[0]
tempint3 = struct.unpack_from(">I", packed)[0]
tempint4 = int.from_bytes(packed, byteorder='big', signed=False)

print(sys.getsizeof(tempint2))
print(tempint2)
print(sys.getsizeof(tempint3))
print(tempint3)
print(sys.getsizeof(tempint4))
print(tempint4)

但是,没有一次尝试(tempint2/tempint3/tempint4)给出我期望的值(4字节大小的整数)。不知怎么说,大小都是18字节(系统获取大小()函数结果)。你能告诉我如何得到预期的答案(4字节或32位大小的整数)?在


Tags: import字节sys整数valfloatstructint
1条回答
网友
1楼 · 发布于 2024-07-04 17:17:59

首先,由于Python的。。。啊哼……”magic“,sys.getsizeof()不会返回listlength,而是返回由Python解释器内部表示的整个数据结构。在

现在,答案(对于整数)很简单。。。(对于Python 2.x/Python 3.x和32位/64位的所有组合):

from math import ceil, floor, log

def minimumAmountOfBytesToHoldTheStuff(x):
    # Avoid math domain errors
    if x < 0:
        x = ~x

    # Avoid more math domain erros
    if x == 0:
        x = 1

    return int(ceil((floor(log(x, 2)) + 1 ) / 8))

def powersOfTwo():
    x = 1
    while True:
        yield x
        x *= 2

def minimumAmountOfBytesToHoldTheStuffOnRealMachines(x):
    bytes = minimumAmountOfBytesToHoldTheStuff(x)
    for power in powersOfTwo():
        if bytes <= power:
            return power

print(minimumAmountOfBytesToHoldTheStuffOnRealMachines(tempint))

注意:似乎log(x, 2)中断了x >= pow(2, 48) - 1,整个算法也是如此。这可能是C库的问题/愚蠢的浮点精度错误,因为Python中的log(n, x)在C中被转换成{}

编辑:这个版本是Python3.x的优化版本,它独立于bot浮点和对数运算,因此在所有情况下都是准确的。。。在

^{pr2}$

其他功能相同。在

我希望这对你有所启示!在

相关问题 更多 >

    热门问题