I wrote this function in php to do the Gray Code of a number:
function c_gray($num){
$bin=decbin($num); //binary of the number
$xor=array();
$xor[]=reset(str_split($bin)); //Get the first bit of binary and put it as the first element of $xor array
for($i=0;$i<strlen($bin)-1;$i++){ //for any bit of the binary
echo $xor[]=$bin[$i] ^ $bin[$i+1]; //do the xor with the next bit of binary and put the result in array $xor
}
$res=implode($xor); //put hte final code in $res
return $res;
}
The problem is with the xor. if I print $xor
array there is just the first element that i put with $xor[]=reset(str_split($bin));
Where I mistake?
Your string elements are not implicitly converted to ints ... try:
function c_gray($num){
$bin = decbin($num); //binary of the number
$xor = array();
$xor[] = reset(str_split($bin)); //Get the first bit of binary and put it as the first element of $xor array
for($i=0;$i < strlen($bin)-1; $i++){ //for any bit of the binary
$xor[] = (int)$bin[$i] ^ (int)$bin[$i+1]; //do the xor with the next bit of binary and put the result in array $xor
}
$res = implode($xor); //put hte final code in $res
return $res;
}