Why xor results are different, 0 becomes 1

折月煮酒 提交于 2020-05-09 11:58:46

问题


i want to make a program like the following picture

and this is my code

<?php

 $iv = 0;
 $Kunci = "U";

 $key =  dechex(ord($Kunci));
 $k =  sprintf("%08d",decbin(hexdec($key)));

 $c0 = sprintf("%08d", decbin($iv));
 $Cip= "0C52CCD7EDB3";
 $Cbs = array();
 $Cbs[0]= $c0;

 $Plaintext = array();
 $Cas = array();
 $P = array();  
 $m= 1;
 $n=1;

//$Cbs= 
$Csplit = str_split($Cip, 2);
$Cas= str_split($Cip,2);

        for ($i=0; $i<count($Csplit); $i++) { 

            $Cbs[$m] = sprintf("%08d",decbin(hexdec($Csplit[$i])));
            $m++;

        }



        for($i=0; $i < count($Cas); $i++){
            $Cas[$i] = sprintf("%08d",decbin(hexdec($Cas[$i])));
            $Cas[$i]=bindec($Cas[$i])>>1;
            if($Cas[$i] % 2 <> 0)$Cas[$i]+=128;
            $Cas[$i]=sprintf("%08d", decbin($Cas[$i]));

        }


 foreach($Cas as $cas_item) {
$prev_c = $Cbs[$n-1];    

$P[$n] = _xor($cas_item, $k);

 $P[$n] = _xor($P[$n], $prev_c);


$Plaintext[$n] = chr(bindec($P[$n]));

 $n++; 
 }

function _xor($text,$key){
for($i=0; $i<strlen($text); $i++){
  $text[$i] = intval($text[$i])^intval($key[$i]);

}
  return $text;
}

print_r($Csplit);
echo "<br/>";
print_r($Cbs);
echo "<br/>";
print_r($Cas);
echo "<br/>";
print_r($P);
echo "<br/>";
print_r($Plaintext);

?>

Cbs = before shift biner Cas = after shift biner and this comes out, the program code works but array 2 and array 5 are wrong. the binary bit code in front should be 0, not 1. Output :

array 2 should be 01110000 instead of 11110000, and array 5 should be 01110100 but result is 11110100. why is 0 in front being 1?


回答1:


When shifting right, beware of the difference of signed and unsigned shift. (also called arithmetic or logical shift)

8-bit value 11101000 right shifted as signed will be 11110100.

The point is if you are shifting a signed value to the right, the uppermost bit is duplicated into the new bits moving in. If you are shifting unsigned values, the uppermost bits move in zeroes.

Languages that lack unsigned integer datatypes have another right-shift operator >>> to indicate that an unsigned (or 'logical') shift is meant. This is the case in PHP and in Java.

This only applies to right-shifts. Never to left. The point is that a right-shift will result in a divide-by-two behaviour.



来源:https://stackoverflow.com/questions/61338787/why-xor-results-are-different-0-becomes-1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!