将字节转换为整数? [英] Convert bytes to int?
问题描述
我目前正在开发一个加密/解密程序,我需要能够将字节转换为整数.我知道:
I'm currently working on an encryption/decryption program and I need to be able to convert bytes to an integer. I know that:
bytes([3]) = b'x03'
然而我不知道如何做相反的事情.我做错了什么?
Yet I cannot find out how to do the inverse. What am I doing terribly wrong?
推荐答案
假设您至少使用 3.2,则有一个 为此内置:
Assuming you're on at least 3.2, there's a built in for this:
int.from_bytes
( bytes
, byteorder
, *, signed=False
)
int.from_bytes
(bytes
,byteorder
, *,signed=False
)
...
参数 bytes
必须是一个类似字节的对象或一个可迭代对象产生字节.
The argument bytes
must either be a bytes-like object or an iterable
producing bytes.
byteorder
参数确定用于表示整数.如果 byteorder
是 big"
,则最高有效字节位于字节数组的开头.如果 byteorder
是 little"
,则最有效字节位于字节数组的末尾.要求主机系统的本地字节顺序,使用 sys.byteorder
作为字节订单价值.
The byteorder
argument determines the byte order used to represent the
integer. If byteorder
is "big"
, the most significant byte is at the
beginning of the byte array. If byteorder
is "little"
, the most
significant byte is at the end of the byte array. To request the
native byte order of the host system, use sys.byteorder
as the byte
order value.
signed
参数表示二进制补码是否用于表示整数.
The signed
argument indicates whether two’s complement is used to
represent the integer.
## Examples:
int.from_bytes(b'x00x01', "big") # 1
int.from_bytes(b'x00x01', "little") # 256
int.from_bytes(b'x00x10', byteorder='little') # 4096
int.from_bytes(b'xfcx00', byteorder='big', signed=True) #-1024
这篇关于将字节转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!