Calculating XOR checksum

Discussion in 'PHP' started by rajoo.sharma, Dec 14, 2007.

  1. #1
    Hi everybody,

    User Otherone helped me yesterday in getting the hex values in variables from other variables not as constants. I'm grateful, thanks Otherone.

    Could you please help me on calculating XOR checksum.

    The following works fine and gives me 0, which means the data is correct and we know by manually calculating it that it is correct. But I'm not able to implement it using a loop, as I really have no idea how long the value will be, it can be just 4 characters long or 100.
    Characters means hex values, a set of 2 each. so in a 4 characters long string we have 2 hex values i.e. a01e will be treated as a0 and 1e.

    Following works fine and gives me 0:

    function checksum($values){
    $stra=substr($values, 0, 2);
    $strb=substr($values, 2, 2);
    $strc=substr($values, 4, 2);
    $strd=substr($values, 6, 2);
    $stre=substr($values, 8, 2);
    $strf=substr($values, 10, 2);
    $strg=substr($values, 12, 2);
    $strh=substr($values, 14, 2);
    $stri=substr($values, 16, 2);
    eval ("\$a = 0x$stra;\$b = 0x$strb;\$c = 0x$strc;\$d = 0x$strd;\$e = 0x$stre;\$f = 0x$strf;\$g = 0x$strg;\$h = 0x$strh;\$i = 0x$stri;");
    echo $a^$b^$c^$d^$e^$f^$g^$h^$i;
    }
    $values="0191050902040843d1";
    checksum($values);


    Following gives 2162888:

    function checksum($values){
    $stra=substr($values, 0, 2);
    $i=2;
    while($i<strlen($values))
    {
    $strb=substr($values, $i, 2);
    $i+=2;
    eval ("\$a = 0x$stra;\$b = 0x$strb;");
    $c=$a^$b;
    $stra=$c;
    }
    echo $stra;
    }
    $values="0191050902040843d1";
    checksum($values);

    Please Help
    Regards
     
    rajoo.sharma, Dec 14, 2007 IP
  2. theOtherOne

    theOtherOne Well-Known Member

    Messages:
    112
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    108
    #2
    Hi,

    as I already wrote you via PM, I was able to sort out this problem as well:

    function checksum($values){	
    	$stra=substr($values, 0, 2);	
    	$i=2;
    	eval ("\$a = 0x$stra;");
    	while($i<strlen($values))
    	{
    		$strb=substr($values, $i, 2);
    		$i+=2;
    		eval ("\$b = 0x$strb;");
    		$c=$a^$b;			
    		$a=$c;
    	}
    	echo $a;
    }
    
    $values="0191050902040843d1";
    checksum($values);
    
    PHP:
    This now returns 0. Your solution didn't work correctly, because when you wrote $stra=$c;, $c was a decimal value. And since 99 in hex (0x99 = 63 dec) is not the same as 99 in decimal (99 dec), your results got all wrong.
     
    theOtherOne, Dec 14, 2007 IP