如何在Python中异或两个包含十六进制数字的字符串? [英] How to XOR two strings that contain hex numbers in python?

查看:428
本文介绍了如何在Python中异或两个包含十六进制数字的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在线寻找答案,但他们中没有一个似乎以我的方式解决了我的问题(我知道,我很挑剔:D)。

以下是处理:我使用字符串类型来存储两个十六进制数字,因为python中的默认整数类型不够我的目的。例如是这样的:

  S1 = 315c4eeaa8b5f8aaf9174145bf43e1784b8fa00dc71d885a804e5ee9fa40b16349c146fb778cdf2d3aff021dfff5b403b510d0d0455468aeb98622b137dae857553ccd8883a7bc37520e06e515d22c954eba5025b8cc57ee59418ce7dc6bc41556bdb36bbca3e8774301fbcaa3b83b220809560987815f65286764703de0f3d524400a19b159610b11ef3e 
S2 = 234c02ecbbfbafa3ed18510abd11fa724fcda2018a1a8342cf064bbde548b12b07df44ba7191d9606ef4081ffde5ad46a5069d9f7f543bedb9c861bf29c7e205132eda9382b0bc2c5c4b45f919cf3a9f1cb74151f6d551f4480c82b2cb24cc5b028aa76eb7b4ab24171ab3cdadb8356f

关键是,这些应该是NUMBERS,但它们存储在一个字符串中。我想要做的是将这两个字符串作为数字处理,然后对两者执行按位XOR,然后以类似的形式获得输出 - 一个存储在字符串中的十六进制数字。



我对编程相当陌生,甚至对Python更新,所以我无法想出一个办法来做到这一点。我不只是在寻找一个脚本,我也想知道它是如何工作的,所以请彻底解释你的解释,因为我很喜欢小白:D。

解决方案

Python 可以将您的值保存为数字。





 >>> hex(int(S1,16))[2:-1] == S1 
True

我只是简单地调整字符串,从头开始删除'0x',从最后删除 L 。 / p>

为了您的答案,您需要做的是,

  hex( int(S1,16)^ int(S2,16))


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).

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. 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. 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.

I am rather new to programming and even newer to python, so I couldn't figure out a way to do this. 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.

解决方案

Python can hold your values as numbers.

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.

For your answer all you need to do is,

hex(int(S1, 16) ^ int(S2, 16))

这篇关于如何在Python中异或两个包含十六进制数字的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆