Javascript - 在不使用 Number(n).toString(2) 的情况下获取指定的位值作为 int
Javascript - get specified bit value as int without using Number(n).toString(2)
在 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
?
取决于结果应该是什么。布尔值 return 就足够了吗?检查指定位置的位是否设置。还是应该输出整数?
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))
const getBit = (num, position) => num >> position & 1;
console.log( getBit(0b1010, 1) )
在 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
?
取决于结果应该是什么。布尔值 return 就足够了吗?检查指定位置的位是否设置。还是应该输出整数?
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))
const getBit = (num, position) => num >> position & 1;
console.log( getBit(0b1010, 1) )