为什么在 3.x 中对二进制数据使用 `ord` 时会出现“TypeError: ord() 预期字符串长度为 1,但找到 int”?
- 2025-02-24 09:30:00
- admin 原创
- 23
问题描述:
我有一些如下代码:
import os, struct, time
# Create a packet by building it with a dummy checksum first,
# then computing and replacing the checksum field.
myChecksum = 0
pid = os.getpid() & 0xFFFF
header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, myChecksum, pid, 1)
data = struct.pack("d", time.time())
csum = 0
countTo = (len(str) / 2) * 2
count = 0
while count < countTo:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
csum = csum + thisVal
csum = csum & 0xffffffff
count = count + 2
# Further logic to compute the replace the dummy checksum within the data
但是在计算的那一行thisVal
,我得到了如下错误:
thisVal = ord(str[count+1]) * 256 + ord(str[count])
TypeError: ord() expected string of length 1, but int found
哪里出了问题?我该如何修复?
解决方案 1:
struct.pack
生成原始二进制数据。在 Python 3.x 中,这由类型表示bytes
;在 2.x 中,bytes
是 的别名str
。
在 Python 3 中,索引bytes
对象将返回字节的整数值:
>>> b"abc"[1]
98
因此,ord
原始代码中的调用是多余的,应该被删除。
相关推荐
热门文章
项目管理软件有哪些?
- 2024年20款好用的项目管理软件推荐,项目管理提效的20个工具和技巧
- 2024年开源项目管理软件有哪些?推荐5款好用的项目管理工具
- 2024年常用的项目管理软件有哪些?推荐这10款国内外好用的项目管理工具
- 项目管理软件有哪些?推荐7款超好用的项目管理工具
- 项目管理软件有哪些最好用?推荐6款好用的项目管理工具
- 项目管理软件哪个最好用?盘点推荐5款好用的项目管理工具
- 项目管理软件排行榜:2024年项目经理必备5款开源项目管理软件汇总
- 项目管理必备:盘点2024年13款好用的项目管理软件
- 项目管理软件有哪些,盘点推荐国内外超好用的7款项目管理工具
- 2024项目管理软件排行榜(10类常用的项目管理工具全推荐)
热门标签
云禅道AD