# Binary xor

• 01-25-2005
gaah
Binary xor
I need to do something similar to this:

string s = "pqr";
s[0] = (char)(s[0] ^ 0xF3);

s[0] has value 0x70 from the begining and I want the result to be 0x83 after running the code. But I get it to be 0xFFFFFF83 instead... Why's that? And more importantly, how do I get rid of it so I only get 0x83? Casting it into a char I think should force it down to one byte, but I can't get it to work...
• 01-25-2005
Sebastiani
0xFFFFFF83 is a 4-byte number - the char is probably being promoted to a larger data-type in the output routine. post the code you are using to print it with.
• 01-25-2005
gaah
string s = "pqr";
printf("%X %X %X \n",s[0],s[1],s[2]);
s[0] = (char)(PWD[0] ^ 0xF3);
printf("%X %X %X \n",s[0],s[1],s[2]);

Like that!
• 01-25-2005
Sebastiani
the %X specifier expects a 4-byte variable to be passed on the stack...try something like this:

Code:

`printf("%X %X %X \n", (unsigned int)((unsigned char)s[0]),(unsigned int)((unsigned char)s[1]),(unsigned int)((unsigned char)s[2]));`
• 01-25-2005
gaah
Yes, that worked... But my main concern is that the string s will be in the right format, meaning only 0x83. And how come it printed it out correctly before I did the xor?
• 01-25-2005
Sebastiani
it probably has something to do with the fact that 0x83 interferes with the char's sign bit, causing the compiler to convert the extra bytes pushed onto the stack into twos-complement form (think it was supposed to be a negative number). the result was the corrupt data output.
• 01-26-2005
winux
Cast as unsigned char
Quote:

Originally Posted by gaah
Yes, that worked... But my main concern is that the string s will be in the right format, meaning only 0x83. And how come it printed it out correctly before I did the xor?

Your char value is defaulted as signed char without the modifier, it is also treated as signed char on operation that most significant bits are set to 0Fh to denote a negative number. Try doing operations on unsigned char or cast as unsigned char when printing.
• 01-26-2005
gaah
But I have it in a string. Can I have unsigned chars in a string?
• 01-26-2005
The Brain
yes.
• 01-26-2005
quzah
You mean "no". If they're using an array of char, and not implicitly stating that it's unsigned, then no, they can't. Not guarinteed anyway. Some implementations may have char signed by default. In short, if you mean unsigned, then say so.

 Hm.. I see the origional post uses the string class. I was thinking in C mode. Nevermind. I'm not intimately familiar with the string class. [/edit]

Quzah.