Probably the best way is through the built-in struct module :
>>> import struct >>> x = 1245427 >>> struct.pack('>BH', x >> 16, x & 0xFFFF) '\x13\x00\xf3' >>> struct.pack('>L', x)[1:] # could do it this way too '\x13\x00\xf3'
Alternatively - and I would usually not recommend this because it is error prone - you can do it "manually" by shifting and chr() :
>>> x = 1245427 >>> chr((x >> 16) & 0xFF) + chr((x >> 8) & 0xFF) + chr(x & 0xFF) '\x13\x00\xf3'
Out of curiosity, why do you need only three bytes? Usually you collect such an integer into a full 32 bits (C unsigned long ) and use struct.pack('>L', 1245427) , but skip step [1:] ?
Ben Hoyt May 10 '09 at 20:42 2009-05-10 20:42
source share