[Tutor] Send binary/hex data to a TCP socket
alan.gauld at btinternet.com
Thu Jan 25 10:34:21 CET 2007
"Tod Haren" <ke7fxl at gmail.com> wrote
>I need to send a server at the other end of a socket a 36 byte
> "frame", where each byte represents a specific field in the custom
> data structure.
If its all single bytes then its fairly easy.
> The documentation for the server says to initialize each field to a
> binary zero(0x00). How do I get a binary zero in Python?
Binary zero is the same as any other zero. So use the char function(to
limit it to a single byte):
Now if you are worried that this looks like more than a single
byte don't be, its not. The \0x is not included its just there for
> A very basic frame looks something like this(modified from
> |00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00
> |00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
> |00 00 00 00 |....
> My problem is that hex(0) return '0x0' and hex(ord('M')) returns
You don't want the hex representation of the data you want the
data in byte format, namely a character.
> 109 bytes instead of 36. The documentation examples are in C++, so
> they are little help to me. The examples make use of the MoveMemory
> function for building the frames, but I'm clueless what that does.
It literally moves blocks of memory around. It workls at
the RAM address level. There is no direct equivalent in Python.
> Pseudo code for the frame above:
> l = 
> for i in xrange(36):
L = [chr(0) for n in range(36)]
L = 'M'
> # I need some other data type to send besides a string!
No a 36 character string is what you want to send.
Don't let the term byte scare you, ascii characters are bytes.
If the data gets more complex and you need to send integers
(4 bytes) etc then you need to look to the struct module.
But for simple byte sequences there's no need.
Author of the Learn to Program web site
More information about the Tutor