Python3二进制文件配对字节数据处理代码修正求助
Fixing Your Binary Data Conversion Code
Let's work through this step by step. I spot several key issues in your current code that are preventing you from getting the expected output, so let's break down the problem and build a correct implementation.
What's Wrong With the Original Code?
- Incorrect iteration method: You're looping through each individual byte instead of processing them as pairs. Your input is structured as groups of two bytes, so we need to iterate with a step of 2 to grab each pair at once.
- Mixed-up byte checks: Your code checks
data[i]wheni%2 !=0(odd indices), which are actually the second bytes of each pair—but your conversion rules are based on the first byte of each pair. This is a core logic mix-up. - Invalid operations in the >1 case: You're trying to slice an integer (
n[0:j]), which doesn't make sense—nhere is the first byte's numeric value, not a byte array. The logic here also doesn't align with your "backtrack from the output result" rule.
Correct Implementation Approach
First, let's restate your conversion rules clearly to ensure alignment:
- Rule 1: For a byte pair
(0, b), appendbdirectly to the output. - Rule 2: For a byte pair
(1, _), append the second byte of the previous pair to the output. - Rule 3: For a byte pair
(n, k)wheren>1: Backtracknpositions from the end of the current output, then takekbytes starting from that position and append them to the output.
Working Code
data = b'\x00\x20\x00\x2A\x02\x01' out = bytearray() # Track the second byte of the previous pair to handle Rule 2 prev_second_byte = None # Iterate over the input data in 2-byte pairs for i in range(0, len(data), 2): first_byte = data[i] second_byte = data[i+1] if first_byte == 0: out.append(second_byte) prev_second_byte = second_byte # Update for potential Rule 2 usage later elif first_byte == 1: # Ensure we have a valid previous pair before appending if prev_second_byte is not None: out.append(prev_second_byte) elif first_byte > 1: # Calculate the starting index in the output (backtrack n positions) start_idx = len(out) - first_byte # Extract k bytes from the output and append them # Note: This assumes your input data is valid (no out-of-bounds errors) bytes_to_add = out[start_idx : start_idx + second_byte] out.extend(bytes_to_add) # Verify the result print(out) # Outputs bytearray(b' * ') which equals b'\x20\x2A\x20'
Key Explanations
- Pair-wise iteration: Using
range(0, len(data), 2)lets us easily access each pair's first and second bytes withdata[i]anddata[i+1]. - Tracking previous bytes: Storing
prev_second_byteensures we can correctly apply Rule 2 by recalling the second byte of the prior pair. - Backtracking logic for Rule 3: We calculate the starting position in the output bytearray by subtracting
first_bytefrom the current length ofout, then slice the required number of bytes (second_byte) and add them to the output.
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

