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

如何修改Python异或处理代码使输出字节数与输入文件一致?

Fixing XOR Output Byte Count Mismatch

Your current code has two main issues causing the output byte count to not match the input:

  1. The first chunk of data is skipped entirely (you call readinto once before the loop but never process it)
  2. Every iteration writes the entire 1024-byte buffer, even when the last chunk has fewer valid bytes.

Here's the corrected version of your code that fixes both problems:

import sys

def XoR(filename, operand):
    byte = bytearray(1024)
    with open(filename, "rb") as file:
        while True:
            reAd = file.readinto(byte)
            if reAd == 0:
                break  # End of file reached
            # XOR only the valid bytes read
            for i in range(reAd):
                byte[i] ^= operand
            # Write only the valid portion of the buffer
            sys.stdout.buffer.write(byte[:reAd])

def main():
    if len(sys.argv) != 3:
        print("Usage: python script.py <filename> <operand>", file=sys.stderr)
        sys.exit(1)
    try:
        operand = int(sys.argv[2])
    except ValueError:
        print("Operand must be an integer", file=sys.stderr)
        sys.exit(1)
    XoR(sys.argv[1], operand)

if __name__ == '__main__':
    main()

Key Changes Explained:

  • Fixed loop logic: Removed the initial readinto call outside the loop, and added a check for reAd == 0 to break the loop when we've reached the end of the file. This ensures all chunks (including the first one) are processed.
  • Write only valid bytes: Instead of writing the entire byte buffer with sys.stdout.buffer.write(byte), we slice it to only include the valid bytes read: byte[:reAd]. This ensures the last chunk only outputs exactly the number of bytes that were actually read from the input file.
  • Added error handling: Added checks for correct command-line arguments and valid integer operand to make the script more robust.

This modified code will produce output with exactly the same number of bytes as the input file, applying the XOR operation correctly to every byte.

内容的提问来源于stack exchange,提问作者Y.M

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:21:57