[英]Python - Integer to bytes object smallest possible size
I'm in a special circumstance where I would like to convert an integer into a bytes object of the smallest length possible.我处于一种特殊情况,我想将 integer 转换为尽可能最小长度的字节 object。 I currently use the following method to covert to bytes:我目前使用以下方法转换为字节:
number = 9847
bytes = number.to_bytes(4, 'little')
However I would like to scale that the amount of bytes used down (the 4) to the smallest possible size.但是,我想将使用的字节数(4)缩小到可能的最小大小。 How can I achieve this?我怎样才能做到这一点?
I figured it out on my own: I use the following function to do the conversion to bytes for me now:我自己想出来的:我现在使用以下 function 为我转换为字节:
import math
def int_to_bytes(self, integer_in: int) -> bytes:
"""Convert an integer to bytes"""
# Calculates the least amount of bytes the integer can be fit into
length = math.ceil(math.log(integer_in)/math.log(256))
return integer_in.to_bytes(length, 'little')
This works because with exponents a = b^e is equivalent to e = log(a)/log(b)这是有效的,因为指数 a = b^e 等价于 e = log(a)/log(b)
In this case our problem is integer_in = 256^e, and we want to solve for e.在这种情况下,我们的问题是 integer_in = 256^e,我们想要求解 e。 This can be solved by rephrasing it to e = log(integer_in)/log(256).这可以通过将其改写为 e = log(integer_in)/log(256) 来解决。 Lastly, we use math.ceil() to round up the answer to an integer.最后,我们使用 math.ceil() 对 integer 的答案进行四舍五入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.