int.to_bytes 相当于小数

问题描述 投票:0回答:1

我需要使用

int.to_bytes
方法,但出现以下错误
OverflowError: int too big to convert
。 因此,我被告知使用速度较慢但可处理更大数字的
Decimal
类,但我找不到与
int.to_bytes
函数完全相同的函数。

这是一个数字较小的代码示例,适用于

to_bytes
但不适用于其他方法:

from decimal import *

message = b"Message"
length = len("Message")

number = int.from_bytes(message, 'little')
print(number) # 28542640894207309

message2 = int.to_bytes(number,length,'little')
print(message2) # b'Message'

message3 = str(Decimal(number)).encode()
print(message3) # b'28542640894207309'

我希望我的第三次打印与第二次打印相同

python encoding byte decimal
1个回答
0
投票

如果您的数字没有小数部分,则此处不需要使用

Decimal

您会得到一个

OverflowError
,因为,“如果整数无法用给定的字节数表示,则会引发溢出错误”,默认为
1
。因此,默认情况下,任何大于 255 的数字都会引发
OverflowError

只需确定您的数字可能具有的最大值(可能低于 2**64),然后使用

bytes
/
int.to_bytes
int.from_bytes
参数,如上所述:

number.to_bytes(8)  # 8 bytes are used to encode the number
© www.soinside.com 2019 - 2024. All rights reserved.