V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
MrgHOST
V2EX  ›  Python

Python 字节流处理

  •  
  •   MrgHOST · 2017-09-10 22:27:25 +08:00 · 4413 次点击
    这是一个创建于 2413 天前的主题,其中的信息可能已经有所发展或是发生改变。

    语言:python

    问题:通过 socket 收到 b'\x7d\x76\x76\x76\x76\x76\x76\x76\x[XOR]\x7d'

    我该如何去处理这串 bytes。

    1 )在 recv 中找到 0x7e 2 )校验 3 )进一步处理

    python 不像 c 那么好处理字节流。 求大神赐教

    11 条回复    2017-09-11 18:38:30 +08:00
    MrgHOST
        1
    MrgHOST  
    OP
       2017-09-10 22:28:28 +08:00
    c 语言可以用 byte*。但 python 我想不出怎么处理
    pepesii
        2
    pepesii  
       2017-09-10 22:48:59 +08:00
    est
        3
    est  
       2017-09-10 23:38:30 +08:00
    > python 不像 c 那么好处理字节流。

    那就用 C 啊。
    junzki
        4
    junzki  
       2017-09-11 11:47:20 +08:00
    C 语言怎么写,Python 也用相同的写法。拿 Python 的 byte 当 C 语言的 char* 用就好了。
    NoAnyLove
        5
    NoAnyLove  
       2017-09-11 12:43:01 +08:00
    没看懂你要做什么,排版看得头疼。。。。。如果收到的数据有固定的结构或者头部,用 struct 根据 field 来拆。如果没有固定的格式,依赖特殊的 magic number,那么无论是 bytes 还是 bytearray 都是可以 find 或者 index 的。

    一句话来说,用 Python 处理数据绝对比用 C 简单啊
    ryd994
        6
    ryd994  
       2017-09-11 14:19:22 +08:00
    @NoAnyLove 定长数据结构在 C 里可以用 union 和 struct 很方便的操作
    只有一个不定长内容在尾部的,也可以
    BBCCBB
        7
    BBCCBB  
       2017-09-11 14:34:40 +08:00
    python3 调用`bytes`的`decode()`方法可以转成`str`,`str`调用`encode()`方法可以转成`bytes`, 问的是这个??
    BBCCBB
        8
    BBCCBB  
       2017-09-11 14:36:20 +08:00
    而且 python 的 bytes 类型也有 find 这种方法
    goofool
        9
    goofool  
       2017-09-11 16:16:50 +08:00   ❤️ 1
    struct + memoryview
    MrgHOST
        10
    MrgHOST  
    OP
       2017-09-11 18:37:36 +08:00
    @goofool 很受启发 谢谢
    MrgHOST
        11
    MrgHOST  
    OP
       2017-09-11 18:38:30 +08:00
    @all。 也谢谢各位
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   928 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:59 · PVG 03:59 · LAX 12:59 · JFK 15:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.