Skip to content Skip to sidebar Skip to footer

Int To Binary Python

This question is probably very easy for most of you, but i cant find the answer so far. I'm building a network packet generator that goes like this: class PacketHeader(Packet): fie

Solution 1:

If you want to convert int or any other primitive data type to binary then the struct module might help you.

http://docs.python.org/library/struct

>>>import struct>>>struct.pack('>i', 257)
'\x00\x00\x01\x01'
>>>struct.pack('<i', 257)
'\x01\x01\x00\x00'
>>>struct.unpack('<i', '\x01\x01\x00\x00')
(257,)
>>>struct.unpack('>i', '\x00\x00\x01\x01')
(257,)

ms4py mentioned you might want to convert 2 byte ints so:

>>>struct.pack('>h', 257)
'\x01\x01'
>>>struct.unpack('>h', '\x01\x01')
(257,)
>>>

oh and:

>>>struct.unpack('>h', '\x10\x00')
(4096,)
>>>

Solution 2:

Solution 3:

Seems to me, that you want an integer to binary converter.

If that's the case, then this should work:

def convert(N):
    if not N:
        return''else:
        return"%s%s" %(convert(N/2), N%2)

Hope this helps

Post a Comment for "Int To Binary Python"