Convert integer to fixed length binary string
Ulrich Eckhardt
eckhardt at satorlaser.com
Thu Jun 11 07:40:48 EDT 2009
casebash wrote:
> I know the bin function converts an int into a binary string.
Binary string sounds ambiguous. Firstly, everything is binary. Secondly,
strings are byte strings or Unicode strings. In any case, I'm not 100% sure
what you mean - giving an example of input and output would help!
> Unfortunately, I need to know the length of the binary string when it
> is being read in and len(bin(x)) depends on x. Is there any way to
> limit it to 4 bytes?
If you need a piece of four bytes which contain a number in a packed format
similar to the one used in memory, using bin(x) is the wrong way. Instead,
take a look at the struct module:
import struct
struct.pack('=L', 255)
Alternatively, also the array module might help.
Uli
--
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932
More information about the Python-list
mailing list