如何修改Python异或处理代码使输出字节数与输入文件一致?
Fixing XOR Output Byte Count Mismatch
Your current code has two main issues causing the output byte count to not match the input:
- The first chunk of data is skipped entirely (you call
readintoonce before the loop but never process it) - 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
readintocall outside the loop, and added a check forreAd == 0to 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
bytebuffer withsys.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
相关产品推荐
相关产品推荐

