How to XOR two strings that contain hex numbers in python?

前端 未结 3 958
轻奢々
轻奢々 2021-01-23 12:07

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 tw

相关标签:
3条回答
  • 2021-01-23 12:31
    1. Reverse both strings to s1_r and s2_r
    2. Do a char by char xor (char1 (from s1_r) xor char2 (from s2_r))
    3. Append result to xor_str
    4. Reverse xor_str
    0 讨论(0)
  • 2021-01-23 12:37

    To perform the XOR operation assuming they are long integers, you can use the long type in Python:

    # 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:
    # '0x1013abb8b0ead34450ee04e8d507fa16552e5aa9f2cc9551acc9d71b646f8a9b4f3548f2068172b201bf0daf75bffffdd0dedd861b9ccbcf7c9ce53e39ecafa9c86880fba0c600778fc7bc6e3bd60c8b0df469f5a7f1da4339f9202bdb43b97b22db69642ce5402b8ce44f86d990dbf5a2L'
    
    0 讨论(0)
  • 2021-01-23 12:43

    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))
    
    0 讨论(0)
提交回复
热议问题