Concatenating two Hex values: TypeError: unsupported operand type(s) for <<: 'str' and 'int'

Concatenating two Hex values: TypeError: unsupported operand type(s) for <<: 'str' and 'int'

在Python2.7

声明:

a = hex(17)<<8 | hex(22)<<10

print(a)

给出:

Traceback (most recent call last):
  File "./prog.py", line 18, in <module>
TypeError: unsupported operand type(s) for <<: 'str' and 'int'

但如果我用真正的十六进制替换它们:

a = 0x11<<8 | 0x12<<10

这有效

hex (..) returns 给你一个字符串,而你正在使用 << 运算符处理一个字符串和一个整数,这里出现错误是正常的。相反,您需要将以十六进制为基数的“十六进制数字字符串”转换为 int,因为您使用的是十六进制数字。

示例:

a = int(hex(17), 16) << 8 | int(hex(22), 16) << 10