[英]How to XOR two strings that contain hex numbers in python?
I have looked for an answer online, but none of them seem to solve my problem in my way (I know, I'm picky :D). 我在网上寻找答案,但他们似乎都没有按我的方式解决我的问题(我知道,我很挑剔:D)。
Here's the deal: I am using the string type to store two hex numbers, because the default integer type in python is not long enough for my purposes. 这是交易:我使用字符串类型来存储两个十六进制数字,因为python中的默认整数类型不够长,不适合我的目的。 For example like this:
例如这样:
S1 = "315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e"
S2 = "234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f"
The point is, that these are supposed to be NUMBERS, but they are stored in a string. 关键是,这些应该是NUMBERS,但它们存储在一个字符串中。 What I want to do, is to treat these two strings as numbers, perform a bitwise XOR on the two and then get an output in a similar form - a hex number stored in a string.
我想要做的是将这两个字符串视为数字,对二者执行按位XOR,然后以类似的形式获得输出 - 存储在字符串中的十六进制数字。
I am rather new to programming and even newer to python, so I couldn't figure out a way to do this. 我对编程很新,甚至比python更新,所以我想不出办法做到这一点。 I am not just looking for a script, I would also like to understand how it works, so please be thorough with your explanation, as I am quite the noob :D.
我不仅仅是在寻找一个剧本,我也想了解它是如何运作的,所以请仔细阅读你的解释,因为我非常喜欢这个剧本:D。
Python can hold your values as numbers. Python 可以将您的值保存为数字。
See this for proof, 见这是为了证明,
>>> hex(int(S1, 16))[2:-1] == S1
True
I'm simply adjusting the string, removing '0x'
from the beginning and L
from the end. 我只是调整字符串,从
'0x'
删除'0x'
从结尾删除L
For your answer all you need to do is, 对于你的答案,你需要做的就是,
hex(int(S1, 16) ^ int(S2, 16))
To perform the XOR operation assuming they are long integers, you can use the long
type in Python: 要假设它们是长整数来执行XOR操作,可以在Python中使用
long
类型:
# Convert the hex string S1 and S2 to longs
l1=long(S1,16)
l2=long(S2,16)
result=hex(l1 ^ l2) # Convert the XOR of the strings
# Output will be:
# '0x1013abb8b0ead34450ee04e8d507fa16552e5aa9f2cc9551acc9d71b646f8a9b4f3548f2068172b201bf0daf75bdddd0dedd861b9ccbcf7c9ce53e39ecafa9c86880fba0c600778fc7bc6e3bd60c8b0df469f5a7f1da4339f9202bdb43b97b22db69642ce5402b8ce44f86d990dbf5a2L'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.