Python 怎么做强制类型转换?

2016-04-20 23:23:07 +08:00
 4179e1
在用 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 不太熟,愣是没找到这该怎么处理。
6840 次点击
所在节点    Python
5 条回复
ChiChou
2016-04-20 23:31:30 +08:00
pimin
2016-04-21 00:39:57 +08:00
4179e1
2016-04-21 09:18:00 +08:00
谢谢, struct 是个办法,找了一下没找到这个模块的代码,可能是用 c 实现的,算了直接用了
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
2017-07-06 22:21:10 +08:00
挖自己的坟,我后来是用 ord 做的,val = ord (header[12]) * 256 + ord (header[13])

只适用于大端字节序比如网络……跟楼上 wingyiu 的方法大约是近似的做法

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/272753

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX