Guaranteeing an n-byte data type?

MRAB google at mrabarnett.plus.com
Fri Jan 9 11:45:04 EST 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.
> 
The send() method takes a bytestring argument (class "str" in Python 
2.x, class "bytes" in Python 3.x), which is a string of 8-bit characters 
(1 byte per character). Just build your bytestring and then send it 
(actually it's better to use sendall() because send() isn't guaranteed 
to send all the bytes in one call).



More information about the Python-list mailing list