Guaranteeing an n-byte data type?

Steve Holden steve at
Fri Jan 9 17:46:52 CET 2009

Evan Jones wrote:
> Hello all,
> I'm trying to use sockets to implement a pre-defined network protocol
> that requires that I send messages of exactly a certain number of bytes.
> In Python, integer values are represented as 4 bytes each (AFAIK.)
> However I don't want to always send 4 bytes: sometimes I want to send
> one byte, or 11 bytes, or 33 bytes, or any other permutation that's not
> a multiple of 4. It seems to make the most sense to use one-byte data
> members and concatenate them before sending.
> This is reasonably easy in C (thanks to the uint8_t data type), but with
> Python I'm not sure how I'd implement it. The send() method in the
> socket module will take any kind of data, but you can't specify the
> number of bytes you want to send, so there's no guarantee as to how many
> you're actually sending (particularly if you're sending a value that's
> regarded in Python as a long integer - who knows how that data is
> actually represented in memory behind the scenes!)
> Perhaps since I'm trying to perform low-level operations, Python is
> simply the wrong tool for this job. However, I'd very much like to write
> this implementation in Python for sake of quick implementation and testing.
In Python 2 you'd use an 8-bit string - though as you surmise you need
access to the conversions to and from the primitive data types. This is
provided  by the struct module.

In Python 3 you'll use a bytes object; in 2.6 and onwards the bytes
syntax can be used to refer to regular strings, to make portability
easier (in Python 3, strings are Unicode by default).

Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC    

More information about the Python-list mailing list