Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverting a binary value of a number

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

like image 230
testjavascript Avatar asked Dec 02 '10 18:12

testjavascript


1 Answers

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));
like image 87
Penny Liu Avatar answered Oct 14 '22 23:10

Penny Liu