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 Run code snippetHide results