You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何Python自动将字节数组转为整数?如何解决该问题?

问题:字节数组元素传递后转为整数,无法按字节比对

我正在编写程序,从两个文件中每次读取16字节数据,与输入的指定字节比对。当第一个文件的16字节块中存在该字节时,需将第二个文件对应位置的字节加入列表。但出现问题:字节数组传递给函数后,元素自动转为整数,导致无法按字节比对。

代码如下:

list = []
def checkoccurence(hexbyte,ciph,block):
    if len(block) > 0:
        block = bytearray(block)
        print(block[0])
    # i = 0
    # while i < len(block):
    #     if int(len(block)) > 0 and int(len(ciph)) > 0:
    #         if ciph[i] == hexbyte:
    #             list.append(block[i])
    #     i += 1
    # return 

def main(): 

    byte = input("Type in the byte to look for as a hex value:")
    file1 = input("File 1")
    file2 = input("File 2")

    readciph = open(file2,'rb') #Open the ciphertext file
 
    with open(file1, 'rb') as f: #Open the plain text file
        stream = []
        while True:
            block = bytearray(f.read(16))
            ciph = readciph.read(16)
            byte = str(byte)
            hexbyte = bytes.fromhex(byte)
            checkoccurence(hexbyte,ciph,block)
            if not block:
                break
        stream += [block]
    print(list)

if __name__ == "__main__":
  main()

目前checkoccurence函数的打印语句输出整数而非字节,导致无法按字节比对。我尝试传递字节到函数,期望输出字节,实际却输出整数。


原因分析

在Python中,bytes和bytearray对象的索引访问返回的都是0-255范围内的整数,这是语言的设计特性。你看到的整数其实是对应字节的二进制数值,并非数据类型错误。比如bytearray(b'\x01')[0]会返回1,而不是单字节的b'\x01'。

你的代码中还有一个隐藏问题:hexbyte是通过bytes.fromhex(byte)生成的bytes对象(长度为1),直接用ciph[i] == hexbyte是把整数和bytes对象比对,永远不会相等。


解决方法

1. 调整比对逻辑,用整数进行匹配

将hexbyte转换成整数,和ciph[i]的整数值比对:

hexbyte_int = hexbyte[0]  # 从bytes对象中取出整数

2. 若需要保存字节而非整数,将整数转回bytes

当你需要把匹配到的元素以字节形式存入列表时,用bytes([block[i]])将整数转回单字节的bytes对象。

3. 修正代码中的其他问题

  • 不要用list作为变量名,这会覆盖Python内置的list类型,改为result_list之类的名称。
  • 用with语句管理readciph文件,避免资源泄漏。
  • 移除循环中无意义的byte = str(byte)操作。

修正后的完整代码:

result_list = []

def check_occurrence(target_byte_int, ciph_block, plain_block):
    if not ciph_block or not plain_block:
        return
    for i in range(len(ciph_block)):
        if ciph_block[i] == target_byte_int:
            # 若要保存整数,直接append(plain_block[i]);若要保存字节,用bytes([plain_block[i]])
            result_list.append(bytes([plain_block[i]]))

def main(): 
    byte_hex = input("Type in the byte to look for as a hex value:").strip()
    file1_path = input("File 1 path:").strip()
    file2_path = input("File 2 path:").strip()

    try:
        target_byte_int = int(byte_hex, 16)
        if not 0 <= target_byte_int <= 255:
            raise ValueError("Hex value must be between 00 and FF")
    except ValueError:
        print("Invalid hex value, please enter a 2-digit hex number (e.g. 0A, FF)")
        return

    with open(file2_path, 'rb') as ciph_file, open(file1_path, 'rb') as plain_file:
        while True:
            plain_block = plain_file.read(16)
            ciph_block = ciph_file.read(16)
            if not plain_block:
                break
            check_occurrence(target_byte_int, ciph_block, plain_block)
    
    print(result_list)

if __name__ == "__main__":
    main()

内容的提问来源于stack exchange,提问作者Fish

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:55:20