Performing a bitwise NOT on arbitrarily long integers
Here’s the surprisingly simple solution to a fairly challenging problem. I do not understand why PHPs GMP extension does not include a gmp_not() function.
function gmp_not($n) {
# convert to binary string
$n = gmp_strval($n, 2);
# invert each bit, one at a time
for($i = 0; $i < strlen($n); $i++) {
$n[$i] = ~$n[$i];
}
# convert back to decimal
return gmp_strval(gmp_init($n, 2), 10);
}
Written on September 4, 2009