Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

PHP XOR operation two numbers

I am trying to xor two values which are like below:

Variable 1 : 6463334891 Variable 2 : 1000212390

When i did xor with these values in php it gives me wrong answer.

It should give me "7426059853"

This is my code

 $numericValue = (int)$numericValue;
 $privateKey = (int)$privateKey;
 echo  "Type of variable 1 ".gettype($numericValue)."<br />";
 echo  "Type of variable 2 ".gettype($privateKey)."<br />";
 $xor_val = (int)$numericValue ^ (int)$privateKey;
 echo "XOR Value :".$xor_val."<br />";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just a total stab into the dark...

You're doing this:

echo "6463334891" ^ "1000212390";

When you want to be doing this:

echo 6463334891 ^ 1000212390;

XOR is an operation on bytes. The byte representation of the integer 6463334891 and the string "6463334891" are very different. Hence this operation will result in very different values depending on whether the operands are strings or integers. If you get your numbers in string form, cast them to an int first:

echo (int)$var1 ^ (int)$var2;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...