我是最新的;我正致力于加密/解密程序,我需要能够将字节转换为整数。我知道:
bytes([3]) = b'\x03'
然而,我无法找到如何做反过来。我做错了什么?
假设你至少有3.2,那就有一个built in for this:
int.from_bytes(bytes,byteorder,*,signed = False)
...
参数bytes必须是类字节对象或可迭代生成字节。
byteorder参数确定用于表示整数的字节顺序。如果byteorder为“big”,则最重要的字节位于字节数组的开头。如果byteorder是“little”,则最重要的字节位于字节数组的末尾。要请求主机系统的本机字节顺序,请使用sys.byteorder作为字节顺序值。
signed参数指示是否使用二进制补码来表示整数。
## Examples:
int.from_bytes(b'\x00\x01', "big") # 1
int.from_bytes(b'\x00\x01', "little") # 256
int.from_bytes(b'\x00\x10', byteorder='little') # 4096
int.from_bytes(b'\xfc\x00', byteorder='big', signed=True) #-1024
int.from_bytes( bytes, byteorder, *, signed=False )
不能和我合作我用这个网站的功能,效果很好
https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python
def bytes_to_int(bytes):
result = 0
for b in bytes:
result = result * 256 + int(b)
return result
def int_to_bytes(value, length):
result = []
for i in range(0, length):
result.append(value >> (i * 8) & 0xff)
result.reverse()
return result