I'm trying to translate this code into python from c,
我正在尝试将此代码从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;
}
What I got:
我得到了什么:
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
problem is I always get ValueError: byte must be in range(0, 256)
.
问题是我总是得到ValueError:byte必须在范围内(0,256)。
So I must be translating this wrong. So what am I missing or is there any way I can make this more efficient? Why is the python code wrong?
所以我一定要翻译这个错误。那么我错过了什么,或者有什么方法可以让我更有效率?为什么python代码错了?
update
更新
new_bytes = struct.unpack('<H', packet_data[1:3])
new_packet.append(new_bytes[0] ^ 0x1234)
I'm getting the first few bytes right with above, but nothing ever right with code below:
我上面的前几个字节正确,但下面的代码没有任何正确的:
new_bytes = struct.unpack('<BB', packet_data[1:3])
new_packet.append(new_bytes[0] ^ 0x12)
new_packet.append(new_bytes[1] ^ 0x34)
So my problem still remains inside the while loop, and the question remains how to do this right:
所以我的问题仍然存在于while循环中,问题仍然是如何做到这一点:
new_bytes = struct.unpack('<L', packet_data[i:i+4])
new_packet.append(new_bytes[0] ^ 0x12345678)
1 个解决方案
#1
1
This line
这条线
new_packet.append(struct.unpack('<H', packet_data[1:3])[0] ^ 0x1234)
tries to append a two-byte value to the byte array. One fix is to append the two bytes of the word separately:
尝试将两个字节的值附加到字节数组。一个解决方法是分别附加单词的两个字节:
# 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)
#1
1
This line
这条线
new_packet.append(struct.unpack('<H', packet_data[1:3])[0] ^ 0x1234)
tries to append a two-byte value to the byte array. One fix is to append the two bytes of the word separately:
尝试将两个字节的值附加到字节数组。一个解决方法是分别附加单词的两个字节:
# 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)