python中0xad_python中的十六进制数的按位XOR

出于性能的目的截断长字符串的长度越短,这里有一个小码基准这两个选择:

#!/bin/python

def hexxorA(a, b):

if len(a) > len(b):

return "".join(["%x" % (int(x,16)^int(y,16)) for (x, y) in zip(a[:len(b)], b)])

else:

return "".join(["%x" % (int(x,16)^int(y,16)) for (x, y) in zip(a, b[:len(a)])])

def hexxorB(a, b):

if len(a) > len(b):

return '%x' % (int(a[:len(b)],16)^int(b,16))

else:

return '%x' % (int(a,16)^int(b[:len(a)],16))

def testA():

strstr = hexxorA("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")

if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):

raise KeyError

return strstr

def testB():

strstr = hexxorB("b4affa21cbb744fa9d6e055a09b562b87205fe73cd502ee5b8677fcd17ad19fce0e0bba05b1315e03575fe2a783556063f07dcd0b9d15188cee8dd99660ee751", "5450ce618aae4547cadc4e42e7ed99438b2628ff15d47b20c5e968f086087d49ec04d6a1b175701a5e3f80c8831e6c627077f290c723f585af02e4c16122b7e2")

if not int(strstr, 16) == int("e0ff3440411901bd57b24b18ee58fbfbf923d68cd88455c57d8e173d91a564b50ce46d01ea6665fa6b4a7ee2fb2b3a644f702e407ef2a40d61ea3958072c50b3", 16):

raise KeyError

return strstr

if __name__ == '__main__':

import timeit

print("Time-it 100k iterations :")

print("\thexxorA: ", end='')

print(timeit.timeit("testA()", setup="from __main__ import testA", number=100000), end='s\n')

print("\thexxorB: ", end='')

print(timeit.timeit("testB()", setup="from __main__ import testB", number=100000), end='s\n')

下面是结果:

Time-it 100k iterations :

hexxorA: 8.139988073991844s

hexxorB: 0.240523161992314s

看起来像'%x' % (int(a,16)^int(b,16))比zip版本更快。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值