1

In javascript you can set and clear an individual bit value without having to use Number(n).toString(2)

const setBit = (num, position) => {
  let mask = 1 << position
  return num |= mask
}

const clearBit = (num, position) => {
  let mask = ~(1 << position)
  return num &= mask
}

Is it possible to get a bit value in a similar way without having to call toString?

2 Answers 2

2

const getBit = (num, position) => num >> position & 1; 

console.log( getBit(0b1010, 1) )

Sign up to request clarification or add additional context in comments.

1 Comment

for bitwise operations, it is more concise.
1

Depending what the result should be. Is a boolean return enough? to check if the Bit at a specified position is set. Or should the output be of the whole number?

const getBit = (num, position) => {
  return (num & (2**position)) > 0;
}

console.info("Number ", 2, " on postion ", 1, getBit (2,1))
console.info("Number ", 2, " on postion ",0 , getBit (2,0))

1 Comment

This looks great! Looks like you could even tweak it to return an int: const getBit = (num, position) => +!!(num & (2**position))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.