Write a program to swap the bits at indices i and j of an integer.

Logic:
A 64-bit integer can be viewed as an array of 64 bits,  with the bit at index 0 corresponding to the least significant bit and the bit at index 63 corresponding to the most significant bit. For this problem, first check the bit at both positions are same or not, if they are same, then do nothing, To check bit at particular bit position you can use this algorithm. After that, swap bit with this algorithm.

Program:

<?php 
$a = 134 ;  // original number 
$i = 2  ; //four bit index from  zero 
$j = 5; 

if ((($a >> $i ) & 1 )  != (($a >> $j ) & 1 )  ) { 
    $b = $a ^ (1 << $i ) | (1 << $j );
    printf("Before swap: %b", $a);
    printf("
After swap: %b", $b);

}else { 
    echo 'Bits at position i and j are equal.';
}

Output:

Before swap: 10000110
After swap: 10100010
Author: Hrishikesh Mishra