Javascript - 将指定的位值作为int而不使用Number(n).toString(2)

时间:2018-05-29 04:11:17

标签: javascript bitwise-operators bitmask

在javascript中,您可以设置和清除单个位值,而无需使用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
}

是否有可能以类似的方式获得一点价值而无需致电toString

2 个答案:

答案 0 :(得分:2)

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

console.log( getBit(0b1010, 1) )
&#13;
&#13;
&#13;

答案 1 :(得分:1)

取决于结果应该是什么。布尔返回是否足够?检查指定位置的位是否已设置。或者输出应该是整数?

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))