Frage

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 />";
War es hilfreich?

Lösung 2

That is because you re hitting the MAXIMUM INTEGER LIMIT which is 2147483647

From the PHP Docs...

The maximum value depends on the system. 32 bit systems have a maximum signed integer range of -2147483648 to 2147483647. So for example on such a system, intval('1000000000000') will return 2147483647. The maximum signed integer value for 64 bit systems is 9223372036854775807.

Thus to handle such big integers you need to make use of an extension like (GMP) GNU Multiple Precision

<?php
$v1="6463334891";
$v2="1000212390";
$a = gmp_init($v1);
$b = gmp_init($v2);
echo gmp_intval($a) ^ gmp_intval($b); //"prints" 7426059853

Else , Switch to a 64-bit system.

Andere Tipps

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;

my solution to maintain the value of big integers is to convert them to binary (with base_convert cause decbin doesnt work) and then make the xor for every bit, to finally convert the string to decimal.

function binxor($w1,$w2)
{
    $x=base_convert($w1, 10, 2);

    $y=base_convert($w2, 10, 2);

    // adjust so both have same lenght

    if (strlen($y)<strlen($x)) $y=str_repeat(0,strlen($x)-strlen($y)).$y;

    if (strlen($x)<strlen($y)) $x=str_repeat(0,strlen($y)-strlen($x)).$x;


    $x=str_split($x);$y=str_split($y);

    $z="";
    for ($k=0;$k<sizeof($x);$k++)
    {
        // xor bit a bit
        $z.=(int)($x[$k])^(int)($y[$k]);
    }

    return base_convert($z,2,10);   
}

Also, to adjust large numbers to 32 bits

bindec(decbin($number))

because decbin cuts the number to 32 automatically.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top