Sending binary/hex through socket (Python)
Question: I'm developing a secure file transfer system with Python and I'm dealing now
with the protocol. My idea is to have something like:

    
    
    [Command:1byte][DataLength:2bytes][Data]
    

My problem is that I have no idea on how to deal with binary/hex in Python.

Imagine that I send a packet which command (in binary) is `00000001` (1byte).
The dataLength = 200 bytes, then, since I have 16bits to store it, I have
`0000000011001000`. So the header is: `000000010000000011001000`. The question
is: how to send that "raw", without coding the 0's and 1's with 1byte each?


Answer: You can use the modules
[`struct`](http://docs.python.org/2/library/struct.html) and
[`array`](http://docs.python.org/2/library/array.html) for this as:

    
    
    >>> from struct import pack, unpack
    >>> from array import array
    >>>
    >>> # byte (unsigned char) + 2 bytes (unsigned short)
    >>> header = pack('BH', 0, 15)
    >>> # array of 15 null byte, you can also use string
    >>> buffer = array('B', '\0' * 15).tostring()
    >>>
    >>> header
    '\x00\x00\x0f\x00'
    >>> buffer
    '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    >>>
    >>> header + buffer
    '\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    >>>
    

You should consider of the byte order. Now to unpack that buffer you can do:

    
    
    >>> package = header + buffer
    >>>
    >>> package
    '\x00\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    >>>
    >>> # unpacking the header
    >>> unpack('BH', package[:4])
    (0, 15)
    >>>
    >>> # unpacking the payload
    >>> array('B', package[4:])
    array('B', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
    >>>
    

