bitwise XOR of hex numbers in python

后端 未结 5 1468
陌清茗
陌清茗 2020-12-02 09:40

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



        
5条回答
  •  旧巷少年郎
    2020-12-02 09:52

    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
    

提交回复
热议问题