1

I have a test which I don't understand what I have to do maybe because I didn't work a lot with bits.

the test is this:

it('you should be able to find the value of a given bit', function() {
    expect(answers.valueAtBit(128, 8)).to.eql(1);
    expect(answers.valueAtBit(65, 1)).to.eql(1);
    expect(answers.valueAtBit(65, 7)).to.eql(1);
    expect(answers.valueAtBit(128, 1)).to.eql(0);
});

and this is the function that they gave to me:

valueAtBit: function(num, bit) {
},

In that function I have to return the value which has to match with the tests.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133

1 Answers1

4

You can convert integers to binary strings like:

let n = 11
let bin = n.toString(2)
console.log(bin)

With that you just need to get the correct character. Assuming your counting from the right (and starting at 1) you can do:

function valueAtBit(num, bit) {
    n = num.toString(2)

    return bit > n.length 
           ? 0 
           : n.toString(2)[n.length - bit]
}
console.log(valueAtBit(11, 1))
console.log(valueAtBit(11, 2))
console.log(valueAtBit(11, 3))
console.log(valueAtBit(11, 4))
console.log(valueAtBit(11, 5)) // all zero after this

Another option if you want to do the math is to divide by the number by 2**bit and take the mod:

function valueAtBit(num, bit) {
    return Math.floor(num / (2 ** bit)) % 2
}

let num = 523
console.log("number in binary:", num.toString(2))

for (let i = 0; i < 10; i++){
    console.log("bit: ", i, valueAtBit(num, i))
}
Mark
  • 90,562
  • 7
  • 108
  • 148