Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,900 questions

51,831 answers

573 users

How to print the bits that need to be flipped to convert a number to another number in PHP

1 Answer

0 votes
function printNeedToBeFlippedBits($num1, $num2) {
    $bitNum = 0;
    $lsb1 = 0;
    $lsb2 = 0;
    
    while (($num1 > 0) || ($num2 > 0)) {
        $lsb1 = $num1 & 1;
        $lsb2 = $num2 & 1;
        
        if ($lsb1 != $lsb2) {
            echo $bitNum . " ";
        }
        
        $num1 = $num1 >> 1;
        $num2 = $num2 >> 1;
        
        $bitNum++;
    }
}

     
$num1 = 2;  // 00000010
$num2 = 17; // 00010001
 
printNeedToBeFlippedBits($num1, $num2);

echo "\n";
 
$num1 = 3;   // 00000011
$num2 = 221; // 11011101
 
printNeedToBeFlippedBits($num1, $num2);

 
 
 
 
/*
run:
    
0 1 4 
1 2 3 4 6 7 
        
*/

 



answered Dec 25, 2023 by avibootz
...