You can use a function that converts numbers to binary as a string, flips the 0s and 1s, then converts back to a number. It seems to give the expected results, but looks pretty ugly:
function flipBits(n) {
return parseInt(n.toString(2).split('').map(bit => 1 - bit).join(''),2)
}
[0,1,2,3,4,5,123,987679876,987679875].forEach(
n => console.log(n + ' -> ' + flipBits(n))
);
Maybe there's a mix of bitwise operators to do the same thing.
Edit
It seems you're working with strings, so just split, flip and join again:
// Requires support for ECMAScript ed 5.1 for map and
// ECMAScript 2015 for arrow functions
function flipStringBits(s) {
return s.split('').map(c => 1 - c).join('');
}
['0','010','110','10011100110'].forEach(
v => console.log(v + ' -> ' + flipStringBits(v))
);
Basic function for ECMAScript ed 3 (works everywhere, even IE 4).
function flipStringBitsEd3(s) {
var b = s.split('')
for (var i = 0, iLen = b.length; i < iLen; i++) {
b[i] = 1 - b[i];
}
return b.join('');
}
// Tests
console.log('Ed 3 version');
var data = ['0', '010', '110', '10011100110'];
for (var i = 0, iLen = data.length; i < iLen; i++) {
console.log(data[i] + ' ->\n' + flipStringBitsEd3(data[i]) + '\n');
}
Works with any length string. The ed 3 version will work everywhere and is probably faster than functions using newer features.