Python 3: how to append number appended to a byte array as bytes -


what i'd want in python script have bytearray , append 2 numbers it, send message, , have receiving c application can read number again.

the c app reads this:

//deserialize srvid end of payload uint16 srvidfrom; uint16 srvidto;  srvidfrom = payload[len-4]  | payload[len-3] << 8; srvidto = payload[len-2]  | payload[len-1] << 8; 

and made python script tries above this:

my_bytes = bytearray() numb = 1 dummysrvid = 1234 srvidfrom = 5678 my_bytes.append(numb) my_bytes.append(dummysrvid & 0xff) my_bytes.append(dummysrvid >> 8) my_bytes.append(srvidfrom & 0xff) my_bytes.append(srvidfrom >> 8) 

but not work. i.e., following code gives following output:

srvidfrom = my_bytes[len(my_bytes)-4] << 8 | my_bytes[len(my_bytes)-3] << 0 srvidto = my_bytes[len(my_bytes)-2] << 8 | my_bytes[len(my_bytes)-1] << 0 print('return packet had srvidfrom {} , srvidto {}'.format(srvidfrom,srvidto)) 

output

return packet had srvidfrom 53764 , srvidto 44 

or stuff similar that. doing wrong?

you appended bytes in following order

my_bytes.append(dummysrvid & 0xff)  # -4 (offset end) my_bytes.append(dummysrvid >> 8)    # -3 my_bytes.append(srvidfrom & 0xff)   # -2 my_bytes.append(srvidfrom >> 8)     # -1 

but in python test decode, shift wrong bytes, swapping msb , lsb parts:

srvidfrom = (     my_bytes[len(my_bytes)-4] << 8   #  -4 dummysrvid & 0xff   | my_bytes[len(my_bytes)-3] << 0   #  -3 srvidfrom >> 8 ) srvidto = (     my_bytes[len(my_bytes)-2] << 8   #  -2 srvidfrom & 0xff   | my_bytes[len(my_bytes)-1] << 0   #  -1 srvidfrom >> 8 ) 

the latter not match c code either; shift little-endian bytes (offsets -3 , -1):

srvidfrom = payload[len-4]  | payload[len-3] << 8; srvidto = payload[len-2]  | payload[len-1] << 8; 

and indeed, if swap shifting , match c code decode, correct values:

>>> my_bytes[len(my_bytes)-4] | my_bytes[len(my_bytes)-3] << 8 1234 >>> my_bytes[len(my_bytes)-2] | my_bytes[len(my_bytes)-1] << 8 5678 

so something else wrong. python encoding work fine.


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -