为什么两个字节类型不能进行异或
我需要一个功能来将所有可能的单字节与字节流进行异或。我有这个函数:
def byteChallenge(text):
for i in range(0xff):
res = ([bytes([i]) ^ bytes([a]) for a in text])
print(res)
其中 text = bytes.fromhex(hexstring)
并且我收到了一个不合理的错误:
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'
bytes[i]
和 bytes[a]< /code> 具有相同的字节类型。 我该如何解决这个问题?
I need a functionality to xor all possible single bytes with a bytestream. I have that function:
def byteChallenge(text):
for i in range(0xff):
res = ([bytes([i]) ^ bytes([a]) for a in text])
print(res)
where text = bytes.fromhex(hexstring)
and I am getting an unreasonable error:
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'
both bytes[i]
and bytes[a]
are of the same bytes type.
How i fix that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以对任意
int
值进行异或,因为作为任意精度值,任何一对int
值都可以被视为具有相同长度的位序列,并用高位 0 填充:需要两个值中较小的一个。不过,字节仅表示字节序列,没有关于这些字节含义的语义。如果两个值的长度相等,您可以计算成对元素的异或。但如果值的长度不同,结果应该是什么?您可以填充较短的序列,但是用什么字节呢?填充应该是序列中的高位字节还是低位字节?
没有明显的答案,因此
bytes
不会尝试强加一个答案。它根本不支持 XOR,而是让用户以 XOR 有意义的方式解释字节。You can XOR arbitrary
int
value because, as arbitrary precision values, any pair ofint
values can be thought of as bit sequences of identical length, with high-order 0s padded as necessary to the smaller of the two value.bytes
, though, just represent sequences of bytes with no semantics about what those bytes mean. If the two values were of equal length, you could compute the XOR of pairwise elements. But if the value are of different lengths, what should the result be? You could pad the shorter sequence, but with what byte(s)? And should the padding be higher- or lower-order bytes in the sequence?There's no obvious answer, so
bytes
doesn't try to impose one. It simply doesn't support XOR, leaving it to the user to interpret the bytes in a way that XOR makes sense.