Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...