向字节数组添加4个字节
我正在尝试把这段代码从C语言翻译成Python。
} else if(remaining == 3) {
firstB = (BYTE*)&buf[0];
*firstB ^= 0x12;
firstW = (WORD*)&buf[1];
*firstW ^= 0x1234;
i = 3;
}
for(; i<len;)
{
then = (DWORD*)&buf[i];
*then ^= 0x12345678;
i += 4;
}
我得到的结果是:
elif remaining == 3:
new_packet.append(struct.unpack('<B', packet_data[0:1])[0] ^ 0x12)
new_packet.append(struct.unpack('<H', packet_data[1:3])[0] ^ 0x1234)
i = 3
while i < packet_len:
new_packet.append(struct.unpack('<L', packet_data[i:i+4])[0] ^ 0x12345678)
i += 4
return new_packet
问题是我总是遇到 ValueError: byte must be in range(0, 256)
的错误。
所以我可能翻译错了。那么我漏掉了什么呢?或者有没有办法让我做得更高效一些?为什么我的Python代码会出错呢?
更新
new_bytes = struct.unpack('<H', packet_data[1:3])
new_packet.append(new_bytes[0] ^ 0x1234)
我用上面的代码得到了前几个字节是对的,但下面的代码却一直不对:
new_bytes = struct.unpack('<BB', packet_data[1:3])
new_packet.append(new_bytes[0] ^ 0x12)
new_packet.append(new_bytes[1] ^ 0x34)
所以我的问题仍然出现在while循环里面,问题是我该怎么做才对:
new_bytes = struct.unpack('<L', packet_data[i:i+4])
new_packet.append(new_bytes[0] ^ 0x12345678)
1 个回答
1
这一行
new_packet.append(struct.unpack('<H', packet_data[1:3])[0] ^ 0x1234)
试图将一个两字节的值添加到字节数组中。一个解决办法是将这个值的两个字节分别添加:
# Little-endian, so the first byte is low byte of the word.
new_bytes = struct.unpack('BB', packet_data[1:3])
new_packet.append(new_bytes[0] ^ 0x34)
new_packet.append(new_bytes[1] ^ 0x12)
# Similarly for the 4-byte value
new_bytes = struct.unpack('BBBB', packet_data[i:i+4])
new_packet.append(new_bytes[0] ^ 0x78)
new_packet.append(new_bytes[1] ^ 0x56)
new_packet.append(new_bytes[2] ^ 0x34)
new_packet.append(new_bytes[3] ^ 0x12)