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);
}
One Comment
→
The gmp_com function calculates one’s compliment (a bitwise NOT). Just remember to mask its result or you’ll end up with a signed integer!
For example:
10011010010is 123411111111111is 2047, my chosen maskecho gmp_strval(gmp_and(gmp_com('1234'), '2047'), 2);>>
1100101101The first line is the original (1234). The second line is its masked bitwise NOT:
1001101001001100101101I find it easier to think of binary in the context of its register. So 2047 is the maximum value an 11-bit register can handle.