Search code examples
c++arrayscharxorunsigned

Xor with unsigned char


I am trying to perform an Xor between a 64 bit key and a 64 bit unsigned char array and I keep getting very strange output. Is there an issue with the data type or the order of operations?

#include <iostream>

using namespace std;

int main() {
    unsigned char inputText = '7';
    unsigned char key = 'a';

    cout << "(input: 0x";
    cout << " " << inputText << ") ^ (";

    cout << "key: 0x";
    cout << " " << key << ") = ";

    cout << "0x ";
    cout << (inputText ^ key);
    cout << endl;
    return 0;
}

Here is the output:

(input: 0x 7) ^ (key: 0x a) = 0x 86

As you can see, xor is producing large integers, and no evidence that the hex values were xor'd. The correct output from xor should be:

0x d

Solution

  • you are not xoring the hex numbers, but the ascii values of the characters.

    input: '7', '3', '6', '5'

    ascii: 55, 51, 54, 53

    key: '0', 'f', 'f', 'a'

    ascii: 48, 102, 102, 97

    result: 55 ^ 48, 51 ^ 102, 54 ^ 102, 53 ^ 97

    result: 7, 85, 80, 84