在python十六进制数字的按位异或 [英] bitwise XOR of hex numbers in python
问题描述
我们如何能够在XOR蟒蛇如十六进制数。我想异或'ABCD'到'12EF'。答案应该是B922。
我用低于code,但它返回垃圾值
DEF strxor(A,B):#XOR不同长度的两个字符串
如果len(一)GT; LEN(b)的
回归。加入([%S%(ORD(X)^ ORD(Y))为(X,Y)的拉链(一[:LEN(B)],B)])
其他:
回归。加入([%S%(ORD(X)为(X,Y)的压缩(A,B [^ ORD(Y)):LEN(一)])])关键='12ef
M1 =ABCD
打印strxor(键,M1)
哇。你真是一个很长的距离过于复杂了。尝试:
>>>打印十六进制(0x12ef ^ 0xabcd)
0xb922
您似乎忽略了这些方便的事实,至少有:
- Python有十六进制整数字面的原生支持,使用
0X
preFIX。 - 十六进制只是一个presentation细节;运算以二进制完成,然后将结果打印为十六进制。
- 有输入(十六进制文字)和输出格式之间没有任何联系,也没有这样的事情在Python变量十六进制数。
- 的
十六进制()
函数可用于任何数字转换成用于显示的十六进制字符串。
如果您已经有数字作为字符串,你可以使用 INT()
函数将转换为数字,通过提供预期的底座(16进制数):
>>>打印INT(12ef,16)
4874
所以,你可以做两次转换,进行异或,然后再转换回十六进制:
>>>打印十六进制(INT(12ef,16)^ INT(ABCD,16))
0xb922
how can we XOR hex numbers in python eg. I want to xor 'ABCD' to '12EF'. answer should be B922.
i used below code but it is returning garbage value
def strxor(a, b): # xor two strings of different lengths
if len(a) > len(b):
return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a[:len(b)], b)])
else:
return "".join(["%s" % (ord(x) ^ ord(y)) for (x, y) in zip(a, b[:len(a)])])
key ='12ef'
m1='abcd'
print strxor(key,m1)
Whoa. You're really over-complicating it by a very long distance. Try:
>>> print hex(0x12ef ^ 0xabcd)
0xb922
You seem to be ignoring these handy facts, at least:
- Python has native support for hexadecimal integer literals, with the
0x
prefix. - "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
- There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
- The
hex()
function can be used to convert any number into a hexadecimal string for display.
If you already have the numbers as strings, you can use the int()
function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):
>>> print int("12ef", 16)
4874
So you can do two conversions, perform the XOR, and then convert back to hex:
>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922
这篇关于在python十六进制数字的按位异或的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!