Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xoring Two characters in PHP?

I was reading about xor in php , and I saw this example:

$aa = "A" ^ "}"; 
echo $aa; // <

So I search in internet about how it works and they said its sum the ascii code , but the above code not sum.

A = 65
} = 125 

65 + 125 = 190

I tried to do sum between another chars like

$aa = "A" ^ "&";
echo $aa;

But the result is 130 = g

so does any char above 97 not sum ?

I also check this questions PHP XOR strings but it didn't help me.

like image 682
learn99 Avatar asked Aug 14 '19 11:08

learn99


2 Answers

The ^ is the exclusive or operator, which means that we're in reality working with binary values. So lets break down what happens.

The XOR operator on binary values will return 1 where just one of the bits were 1, otherwise it returns 0 (0^0 = 0, 0^1 = 1, 1^0 = 1, 1^1 = 0).

As you said yourself, when you use XOR on characters, you're using their ASCII values. These ASCII values are integers, so we need to convert those to binary to see what's actually going on. Let's use your first example, A and }.

$first = 'A';
$second = '}';

$ascii_first = ord($first);    // 65
$ascii_second = ord($second);  // 125

We then convert these to binary using the decbin() function.

$binary_first = decbin($ascii_first);   // 1000001
$binary_second = decbin($ascii_second); // 1111101

Now we use the XOR operator on those binary values.

first      1000001
           ^
second     1111101
-------------------
result     0111100

We see the binary value we get is 0111100. Using the bindec() function we reverse it back to an integer value

$final_ascii = bindec("0111100");   // 60

We see we get the integer value 60 back. Using chr(60) you will get the character which has the decimal value of 60 in the ASCII table - the result is <.

Here's a live demo that shows the steps: https://3v4l.org/Xd8SP - you can play around with it, substituting characters to see the end result of different combinations of characters.

like image 168
Qirel Avatar answered Sep 27 '22 20:09

Qirel


A ascii => 65 decimal => 1000001 binary.

} ascii => 125 decimal => 1111101 binary.

We then do 1000001 xor 1111101 which is 0111100. Bits that are set in A or } but not both are set.

0111100 binary => 60 decimal => < in ascii.

like image 25
KIKO Software Avatar answered Sep 27 '22 19:09

KIKO Software