Home > Net >  send integers via python socket module
send integers via python socket module

Time:08-16

I am trying to send signed integers from python to a PCB. I want to send the number 01 via python, but my PCB keeps interpreting it as "12592" when I write that in binary, that is: 00110000 00110001"

each byte is 48 and 49 - those are the ascii values for 0 and 1 - so the format is what is wrong - I litteraly want to send 10000000 and 10000001 instead, such the PCB interprets it correctly

my code is pretty simple at the moment - i am "send" funciton from the python socket module, and writing socket.send(b'01') - however, i cannot find any other functions in the socket module to do this? is there some way to ask it to send it as signed int instead?

CodePudding user response:

@Laurent H. in the comments above, is exactly right. You want to send binary values, not the binary equivalent of ascii codes for number characters.

 bytes([0,1]) == b'\x00\x01'

which is not what you were sending.

Conversely,

ord("0") == 48

Is the numerical value that gets you the character for zero.

Actually, you could even send binary directly, here with your signs applied:

0b10000000, 0b10000001 == (128, 129)
b'\x80\x81'  # as byte values

CodePudding user response:

If you sent b'01' that sends the literal ASCII byte values 0x30, 0x31. 12592 == 0x3130 which is the little-endian binary interpretation of those bytes.

Use the struct.pack('<h', n) function to pack the integer n as a little-endian signed 16-bit integer.

Examples:

>>> import struct
>>> struct.pack('<h', 1)
b'\x01\x00'
>>> struct.pack('<h', 0x1213)
b'\x13\x12'
  • Related