推荐学习书目
› 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
4179e1
V2EX  ›  Python

Python 怎么做强制类型转换?

  •  
  •   4179e1 · Apr 20, 2016 · 7915 views
    This topic created in 3817 days ago, the information mentioned may be changed or developed.
    在用 python 写一个抓包程序,把整个以太网数据包作为 string 读进来,其中 12 和 13 字节组合在一起应该是一个短整形(以太网帧里面的类型字段),假如我这个 string 叫做 header ,这个值应该是 header[12:14],怎么样可以把他当作一个整数读进来?

    用 int()直接转会报错:
    self.type_ = socket.ntohs (int(seg[12:14]))
    ValueError: invalid literal for int() with base 10: '\x08\x06'


    C 里面是很简单,创建一个 short 的类型的指针直接指向这个地址: unsigned short * p = (unsigned short *)&header[12]

    对 python 不太熟,愣是没找到这该怎么处理。
    5 replies  •  2017-07-06 22:21:10 +08:00
    ChiChou
        1
    ChiChou  
       Apr 20, 2016
    4179e1
        3
    4179e1  
    OP
       Apr 21, 2016
    谢谢, struct 是个办法,找了一下没找到这个模块的代码,可能是用 c 实现的,算了直接用了
    wingyiu
        4
    wingyiu  
       Apr 21, 2016
    In Python 3.2 and later, use

    >>> int.from_bytes(b'y\xcc\xa6\xbb', byteorder='big')
    2043455163
    4179e1
        5
    4179e1  
    OP
       Jul 6, 2017
    挖自己的坟,我后来是用 ord 做的,val = ord (header[12]) * 256 + ord (header[13])

    只适用于大端字节序比如网络……跟楼上 wingyiu 的方法大约是近似的做法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   763 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 21:27 · PVG 05:27 · LAX 14:27 · JFK 17:27
    ♥ Do have faith in what you're doing.