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
4179e1
V2EX  ›  Python

Python 怎么做强制类型转换?

  •  
  •   4179e1 · 2016-04-20 23:23:07 +08:00 · 6820 次点击
    这是一个创建于 2950 天前的主题,其中的信息可能已经有所发展或是发生改变。
    在用 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 条回复    2017-07-06 22:21:10 +08:00
    ChiChou
        1
    ChiChou  
       2016-04-20 23:31:30 +08:00
    4179e1
        3
    4179e1  
    OP
       2016-04-21 09:18:00 +08:00
    谢谢, struct 是个办法,找了一下没找到这个模块的代码,可能是用 c 实现的,算了直接用了
    wingyiu
        4
    wingyiu  
       2016-04-21 17:49:00 +08:00
    In Python 3.2 and later, use

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

    只适用于大端字节序比如网络……跟楼上 wingyiu 的方法大约是近似的做法
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2267 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 19ms · UTC 12:47 · PVG 20:47 · LAX 05:47 · JFK 08:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.