Q:

appending 4 bytes to byte array

I'm trying to translate this code into python from c,
} 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).
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?

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:
new_bytes = struct.unpack('<L', packet_data[i:i+4])
new_packet.append(new_bytes[0] ^ 0x12345678)

A:

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)       

