将字节转换为整数?
- 2025-02-07 08:44:00
- admin 原创
- 59
问题描述:
我目前正在开发一个加密/解密程序,我需要能够将字节转换为整数。我知道:
bytes([3]) = b'x03'
但我找不到如何做相反的事情。我做错了什么?
解决方案 1:
假设你至少使用 3.2 版本,则有一个内置功能:
int.from_bytes
(bytes
,,byteorder
,signed=False
*)...
参数
bytes
必须是字节类对象或生成字节的可迭代对象。该
byteorder
参数确定用于表示整数的字节顺序。如果byteorder
为"big"
,则最高有效字节位于字节数组的开头。如果byteorder
为"little"
,则最高有效字节位于字节数组的末尾。要请求主机系统的本机字节顺序,请使用sys.byteorder
作为字节顺序值。该
signed
参数表示是否使用二进制补码来表示整数。
## 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
解决方案 2:
字节列表是可下标的(至少在 Python 3.6 中)。这样,您可以单独检索每个字节的十进制值。
>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist) # b'@x04x1axa3xff'
>>> for b in bytelist:
... print(b) # 64 4 26 163 255
>>> [b for b in bytelist] # [64, 4, 26, 163, 255]
>>> bytelist[2] # 26
解决方案 3:
list()
可用于将字节转换为 int(适用于 Python 3.7):
list(b'x03x04x05')
[3, 4, 5]
解决方案 4:
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
解决方案 5:
在处理缓冲数据时我发现这很有用:
int.from_bytes([buf[0],buf[1],buf[2],buf[3]], "big")
假设中的所有元素buf
都是8位长。
解决方案 6:
将字节转换为位串
format(int.from_bytes(open('file','rb').read()),'b')
解决方案 7:
这是我在寻找现有解决方案时偶然发现的一个老问题。我提出了自己的解决方案,并想与大家分享,因为它允许您根据字节列表创建 32 位整数,并指定偏移量。
def bytes_to_int(bList, offset):
r = 0
for i in range(4):
d = 32 - ((i + 1) * 8)
r += bList[offset + i] << d
return r
解决方案 8:
#convert bytes to int
def bytes_to_int(value):
return int.from_bytes(bytearray(value), 'little')
bytes_to_int(b'xa231')
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD