Saturday, April 6, 2013

XOR in Loosely type Language (PHP)

Recent days, i have to perform exclusive OR (XOR) operation between two numbers. One of them is Hex. and other one is in decimal i.e. in base 10. In PHP, we use ^ operator to perform exclusive OR operation.

Just for reminder, in XOR we get true if and only if exactly one of two bit is true. For further clarification look at below truth table:


ABA xor B
TTF
TFT
FTT
FFF

Now, consider we have to xor F(15 in base 10) with 8. The answer should be 7. I write following code in PHP to do this:
echo "F" ^ "8";
The answer would not be 7. Why? In fact, here, PHP is taking the ascii value of "F" and "8" and then performing xor in between those ascii value.

Now if we have to do correct xor then use following code:
echo 0xF ^ 8;

In fact, above example is too much simple. One may ask if we know a number then why we should cast it to string and then perform xor operation? The answer is simple, in many cases we have to read the numbers from some other stream like network or input etc. There most of the time we get string and PHP does not know "F" in a string is Hex. or it is a character. We can use dechex and hexdec functions in PHP for conversion in these cases

No comments: