[Tutor] Send binary/hex data to a TCP socket

Alan Gauld 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):

>>> char(0)

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

>>> len(chr(0))

> A very basic frame looks something like this(modified from 
> documentation):
>    |00 00 00 00 4D 00 00 00 00 00 00 00 00 00 00 00 
> |....M...........
>    |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
> '0x4d'.

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.append(hex(0))

L = [chr(0) for n in range(36)]

>  l[4]=hex(ord('M'))

L[4] = 'M'

>  d=''.join(l)

> # 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.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list