INT二进制蟒蛇 [英] int to binary python

查看:192
本文介绍了INT二进制蟒蛇的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题可能是对你最很容易,但我无法找到答案为止。

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))

不幸的是,在电线上,我有 \\ X32 \\ X35 \\ X37 (257 十六进制),而不用这一点: \\ X01 \\ X01

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

在此先感谢!

推荐答案

如果要转换 INT 或其它任何原始数据类型为二进制那么结构模块可能会帮助你。

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 提到你可能要转换的2字节整数这样:

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

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

哦和:

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

这篇关于INT二进制蟒蛇的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆