如何用python对二进制文件进行异或
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19414093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to xor binary with python
提问by
I'm trying to xor 2 binaries using python like this but my output is not in binary any help?
我正在尝试像这样使用 python 对 2 个二进制文件进行异或处理,但我的输出不是二进制文件有什么帮助吗?
a = "11011111101100110110011001011101000"
b = "11001011101100111000011100001100001"
y = int(a) ^ int(b)
print y
采纳答案by Rob?
a = "11011111101100110110011001011101000"
b = "11001011101100111000011100001100001"
y = int(a,2) ^ int(b,2)
print '{0:b}'.format(y)
回答by dansalmo
Since you are starting with strings and want a string result, you may find this interesting but it only works if they are the same length.
由于您从字符串开始并想要一个字符串结果,您可能会发现这很有趣,但它仅在它们的长度相同时才有效。
y = ''.join('0' if i == j else '1' for i, j in zip(a,b))
If they might be different lengths you can do:
如果它们的长度可能不同,您可以执行以下操作:
y = ''.join('0' if i == j else '1' for i, j in zip(a[::-1],b[::-1])[::-1])
y = a[len(y):] + b[len(y):] + y
回答by BigH
To get the Xor'd binary to the same length, as per the OP's request, do the following:
要根据 OP 的请求将 Xor'd 二进制文件的长度设为相同,请执行以下操作:
a = "11011111101100110110011001011101000"
b = "11001011101100111000011100001100001"
y = int(a, 2)^int(b,2)
print bin(y)[2:].zfill(len(a))
[output: 00010100000000001110000101010001001]
Convert the binary strings to an integer base 2, then XOR
, then bin()
and then skip the first two characters, 0b
, hence the bin(y0)[2:]
.
After that, just zfill
to the length - len(a)
, for this case.
将二进制字符串转换为以 2 为底的整数XOR
,然后是bin()
,然后跳过前两个字符0b
,因此bin(y0)[2:]
.
之后,只是zfill
到长度 - len(a)
,对于这种情况。
Cheers
干杯