I have a list of numbers that I would like to send to the socket connection as binary data.
As an example, I start with the following list:
data = [2,25,0,0,ALPHA,0,23,18,188]
The above ALPHA list can have any value between 1 and 999. I originally converted this to a string using
hexdata = ''.join([chr(item) for item in data])
So, if ALPHA is 101, this will return the following line:
>>> data = [2,25,0,0,101,0,23,18,188] >>> hexdata = ''.join([chr(item) for item in data]) >>> hexdata '\x02\x19\x00\x00e\x00\x17\x12\xbc'
This works fine, and '\ x02 \ x19 \ x00 \ x00e \ x00 \ x17 \ x12 \ xbc' is the line I need to send.
However, this does not work for ALPHA values ββthat exceed 255 because it is outside the range of the chr statement. If, for example, ALPHA were 999, I would like to get the following line:
data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00\x03\xed\x00\x17\x12\xbc'
I looked at the documentation for struct.pack (), but I cannot figure out how this can be used to achieve the above line. ALPHA is the only variable in the list.
Any help would be greatly appreciated.
EDIT 1
What kind of behavior do you want? Anything between 256 and 65535 takes 2 bytes to represent. Do you want to unpack it the other side? Update the message with your intentions. - gahooa 1 min. Back
That's right, since 999 is above threshold 256, it is represented by two bytes:
data = [2,25,0,0,999,0,23,18,188] hexdata = '\x02\x19\x00**\x03\xed**\x00\x17\x12\xbc'
It makes sense?
As for unpacking, im only sends this data to the socket, I get the data, but this has already been taken care of.
EDIT 2
The string I am sending is always of a fixed length. For simplicity, I find it best to present the list as follows:
ALPHA = 101 data = [25,alpha1,alpha2,1] hexdata = '\x19\x00e\x01' ALPHA = 301 data = [25,alpha1,alpha2,1] hexdata = 'x19\x01\x2d\x01'
as you can see in the hexdata line, it will look like this: \ x01 \ x2d \
If ALPHA <256, alpha1 = 0.