gpt4 book ai didi

python - Python:如何从4字节字节数组中获取4字节大小的整数?

转载 作者:行者123 更新时间:2023-12-03 12:04:37 25 4
gpt4 key购买 nike

这是我编写的一个简单的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个字节(sys.getsizeof()函数结果)。您能告诉我如何获得预期的答案(4字节或32位整数)吗?

最佳答案

首先,由于Python的... ahem ...“魔术”,sys.getsizeof()不会返回lenlist gth,而是sizeof整个数据结构,由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中的 log(n) / log(x)

编辑:这是Python 3.x的优化版本,独立于bot浮点运算和对数运算,因此在所有情况下都是准确的...
from math import ceil

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(x.bit_length() / 8))

其他功能相同。

我希望这能给您带来启发!

关于python - Python:如何从4字节字节数组中获取4字节大小的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33556241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com