cnaol
V2EX  ›  问与答

学 Python 中 有个问题困扰一天了 关于编码的 使用的 python3

  •  
  •   cnaol · Dec 10, 2017 · 2419 views
    This topic created in 3081 days ago, the information mentioned may be changed or developed.
    我现在想达到一个效果
    说具体点 我想把整数 12 转成字节 以 4 个字节保存
    因为客户端 在收到字节流后 读取前 4 个字节保存为长度
    我尝试了好几种转换 都是 ascii

    使用的 py3
    3 replies    2017-12-11 12:38:53 +08:00
    ysc3839
        1
    ysc3839  
       Dec 10, 2017   ❤️ 1
    https://docs.python.org/3/library/struct.html

    >>> import struct
    >>> struct.pack('!i', 12)
    b'\x00\x00\x00\x0c'

    '!i' 的含义: '!' 代表网络字节序,因为你要跟客户端通信,所以得考虑字节序的问题;'i' 代表 int。在前面的链接里都有提到。
    cnaol
        2
    cnaol  
    OP
       Dec 11, 2017
    @ysc3839
    万分感谢
    ysc3839
        3
    ysc3839  
       Dec 11, 2017 via Android
    @cnaol 上面的代码转换成了网络字节序,客户端那里也要转换一次。使用 ntohl 这个函数来转换。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1774 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:17 · PVG 00:17 · LAX 09:17 · JFK 12:17
    ♥ Do have faith in what you're doing.