I would like first to convert a number to binary, then invert it bitwise. Like this:
Number is 793 = 1100011001
then convert the binary value into: 0011100110
In JavaScript I can do the following:
var x = 793;
document.write(x.toString(2)); // gives 0011100110
This will give me the binary value of the number. But how do I invert the binary bitwise?
I tried the ~
operator, but not working probably. The output is: -1100011010
Not the shortest code but more readable. My technique is similar to @Ivo Wetzel:
const bitwiseComplement = (N) => {
let binary = N.toString(2); // 793 is "1100011001" in binary
binary = binary.split('').map(x => {
return (x == 1) ? 0 : 1;
}).join('');
return binary; // with complement "0011100110" in binary
};
console.log(bitwiseComplement(793));
One-liner javascript solution. Regex /[0-1]/g
means match a single character present in the list below [0-1]
.
const bitwiseComplement = (N) => {
return N.toString(2).replace(/[0-1]/g, (v) => (v == 1 ? 0 : 1));
};
console.log(bitwiseComplement(793));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With