在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
?
答案 0 :(得分:2)
const getBit = (num, position) => num >> position & 1;
console.log( getBit(0b1010, 1) )
&#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))