问题
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):
fields = OrderedDict([
("head", "\x00"),
("headpad", "\x00"),
("headlen", "\x1a\x00" ),
("presentflag", "\x2e"),
("timestamp", "\x43\x10\x58\x16\xa1\x01\x00\x00"),
("flag", "\x03"),
("Sequencenum", "\x04\x00"),
])
Later, I call my class and send the packet like this:
send(PacketHeader(Sequencenum=257))
send(PacketHeader(Sequencenum=258))
send(PacketHeader(Sequencenum=259))
Unfortunatly, on the wire i have \x32\x35\x37
(257 in hex
) instead of having this :\x01\x01
.
What i would like to do, is being able to:
send(PacketHeader(Sequencenum=257+1))
and have it converted to int correctly on the wire
Thanks in advance !
回答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,)
>>>
回答2:
If you have an integer and want hex:
hex(257)
'0x101'
Other way around
int('0x101', 16)
257
回答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
来源:https://stackoverflow.com/questions/11421735/int-to-binary-python