int to binary python

时光怂恿深爱的人放手 提交于 2020-01-07 08:13:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!