推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
cqcsdzmt
V2EX  ›  Python

新手求助 Python 数据格式转换的问题。

  •  
  •   cqcsdzmt · Aug 17, 2018 · 2725 views
    This topic created in 2861 days ago, the information mentioned may be changed or developed.
    新手求助 python 数据格式转换的问题。
    最近写一个自己用的上位机脚本,如下:
    xxxx 省略
    str = "this is udp client data\n"
    socket.sendto(str, self.addr)
    xxxx 省略
    现在需要在 str 前面加上十六进制包头,包头如下:
    flag 4 个字节 内容为 0xad 0x0e 0xfd 0x23
    str 数据长度 两个字节表示
    类型 4 个字节 0x00 0x00 0x00 0x01
    预留 4 个字节 0x00 0x00 0x00

    请问需要这么组装啊,试了一上午都没有成功
    12 replies    2018-08-17 14:42:07 +08:00
    cqcsdzmt
        1
    cqcsdzmt  
    OP
       Aug 17, 2018
    另外,如果接收同样带包头的数据,怎么把包头单独掐出来挨个解析呢?
    codechaser
        2
    codechaser  
       Aug 17, 2018 via Android
    是要把这个包转换成 str 加到字符串前面?
    ebingtel
        3
    ebingtel  
       Aug 17, 2018
    struct 试试?
    anjianshi
        4
    anjianshi  
       Aug 17, 2018   ❤️ 1
    content = "this is udp client data\n"

    flag = b'\xad\x0e\xfd\x23'

    hex_t = hex(len(content))[2:].zfill(4)
    len_hex = chr(int(hex_t[:2], 16)) + chr(int(hex_t[2:4], 16))
    len_hex = len_hex.encode()

    type_ = b'\x00\x00\x00\x01'
    rest = b'\x00\x00\x00\x00'

    result = flag + len_hex + type_ + rest + content.encode()
    print(result)
    anjianshi
        5
    anjianshi  
       Aug 17, 2018
    @cqcsdzmt 把 str 转换成 bytes,然后在前面拼接其他 bytes 就行了。上面这个是 Python 3 代码
    HelloAmadeus
        6
    HelloAmadeus  
       Aug 17, 2018 via Android
    struct 模块了解一下,这是 Python2 吗,str 竟然可以直接发送
    a132811
        7
    a132811  
       Aug 17, 2018
    用 Python3 bytes 就解决问题了。更复杂的转换,用 struct。https://ahuigo.github.io/#/post/py/py-str-struct.md
    cqcsdzmt
        8
    cqcsdzmt  
    OP
       Aug 17, 2018
    @anjianshi 非常谢谢你,我用的是 python2.7 也是可以用的吧?我去试一下
    cqcsdzmt
        9
    cqcsdzmt  
    OP
       Aug 17, 2018
    @HelloAmadeus 对,Python2
    cqcsdzmt
        10
    cqcsdzmt  
    OP
       Aug 17, 2018
    @a132811 我是 Python2.7 哦
    cqcsdzmt
        11
    cqcsdzmt  
    OP
       Aug 17, 2018
    @codechaser 不一定非要转换成 str,只在发送时在前面加上包头就可以
    a132811
        12
    a132811  
       Aug 17, 2018
    不是年久失修的老破烂项目,就装 python3 吧,又不困难。python2 这些恶心的字符问题,我才不想面对呢
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1015 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 19:25 · PVG 03:25 · LAX 12:25 · JFK 15:25
    ♥ Do have faith in what you're doing.