How to toggle a bit at specific position in PHP

1 Answer

0 votes
<?php

function print_bits($n, $width = 8) {
    $bin = decbin($n);
    $bin = str_pad($bin, $width, "0", STR_PAD_LEFT);
    echo $bin . "\n";
}

$n = 365;
$pos = 2;

print_bits($n, 12); // print full 12-bit form

$n ^= (1 << $pos);

print_bits($n, 12);


/*
run:

000101101101
000101101001

*/

 



answered Mar 20, 2019 by avibootz
edited Apr 3 by avibootz
...