挑战:
在两个大小相等的缓冲区上执行按位XOR.缓冲区将需要是python str
类型,因为传统上它是python中数据缓冲区的类型.将结果值作为a返回str
.尽快做到这一点.
输入是两个1兆字节(2**20字节)的字符串.
挑战是使用python或现有的第三方python模块(轻松的规则:或创建自己的模块)大幅击败我的低效算法.边际增加是无用的.
from os import urandom
from numpy import frombuffer,bitwise_xor,byte
def slow_xor(aa,bb):
a=frombuffer(aa,dtype=byte)
b=frombuffer(bb,dtype=byte)
c=bitwise_xor(a,b)
r=c.tostring()
return r
aa=urandom(2**20)
bb=urandom(2**20)
def test_it():
for x in xrange(1000):
slow_xor(aa,bb)
Run Code Online (Sandbox Code Playgroud) 我知道有一个内置的xor运算符可以用Python导入.我正在尝试执行xor加密/解密.到目前为止,我有:
def xor_attmpt():
message = raw_input("Enter message to be ciphered: ")
cipher = []
for i in message:
cipher.append(bin(ord(i))[2::])#add the conversion of the letters/characters
#in your message from ascii to binary withoout the 0b in the front to your ciphered message list
cipher = "".join(cipher)
privvyKey = raw_input("Enter the private key: ")
keydecrypt = []
for j in privvyKey:
keydecrypt.append(bin(ord(j))[2::]) #same
keydecrypt = "".join(keydecrypt )#same
print "key is '{0}'" .format(keydecrypt) #substitute values in string
print "encrypted text is '{0}'" .format(cipher) …
Run Code Online (Sandbox Code Playgroud) 我想我了解 python 字节对象,但支持字节字符串的按位操作似乎是一个如此明显的功能。我不明白为什么它不受支持。
>>>'abcdefg'.encode('ascii')
b'abcdefg'
Run Code Online (Sandbox Code Playgroud)
好的。我从一个字符串变成了像我的字符串在 ascii 中的字节表示。
所以当我尝试:
>>> a = 'abcdefg'.encode('ascii')
>>> a ^ a
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'bytes' and 'bytes'
Run Code Online (Sandbox Code Playgroud)
为什么?为什么python不支持这个?关于字节对象,我有什么不明白的地方使这不可行或不明确吗?
python ×3
algorithm ×1
bitwise-xor ×1
byte ×1
bytearray ×1
encryption ×1
performance ×1
python-2.7 ×1
xor ×1