Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert unsigned arbitrary binary bits in javascript

Tags:

javascript

For instance, 10100 would be inverted to 01011; 010 would be inverted to 101; 101 would be converted to 010.

The problem is when I use ~5, it becomes -6 because js uses 32 bit signed.

How do I invert an unsigned arbitrary-bit binary number?

I would like to create a function that takes in this unsigned arbitrary-bit binary number and return its inverted form( 101->010)

I want to convert from string 101 to 010

like image 792
Zac Uwyo H Avatar asked Jan 04 '23 11:01

Zac Uwyo H


2 Answers

You can create a function that flips the required number of digits like so

    var flipbits = function (v, digits) {
        return ~v & (Math.pow(2, digits) - 1);
    }
    console.log(flipbits(5, 3)); // outputs 2
    console.log(flipbits(2, 3)); // outputs 5

note - this isn't "arbitrary number of bits" ... it's 32 at best

working with strings, you can have arbitrary bit length (this one wont work without transpiling in Internet Exploder)

    var flipbits = str => str.split('').map(b => (1 - b).toString()).join('');

    console.log(flipbits('010')); // outputs 101
    console.log(flipbits('101')); // outputs 010

The above in ES5

    var flipbits = function flipbits(str) {
      return str.split('').map(function (b) {
        return (1 - b).toString();
      }).join('');
    };

    console.log(flipbits('010')); // outputs 101
    console.log(flipbits('101')); // outputs 010
like image 181
Jaromanda X Avatar answered Jan 07 '23 11:01

Jaromanda X


Inverting the bits will always be the same, but to convert an unsigned integer to a signed integer you can use the unsigned >>> shift operator to work on unsigned numbers:

console.log(~5);     // -6
console.log(~5>>>0); // 4294967290

If you want to make sure you only flip the significant bits in the number, you'll instead want to mask it via an & operation with how many significant bits you need. Here is an example of the significant bit masking:

function invert(x) {
  let significant = 0;
  let test = x;

  while (test > 1) {
    test = test >> 1;
    significant = (significant << 1) | 1;
  }

  return (~x) & significant;
}

console.log(invert(5));  // 2 (010 in binary)
like image 31
Liam Gray Avatar answered Jan 07 '23 12:01

Liam Gray