Rob*_*cks 57 javascript numbers bit-manipulation
如何在JavaScript中设置,清除,切换和检查一下?
cle*_*tus 173
得到一点面具:
var mask = 1 << 5; // gets the 6th bit
Run Code Online (Sandbox Code Playgroud)
要测试是否设置了一个位:
if ((n & mask) != 0) {
// bit is set
} else {
// bit is not set
}
Run Code Online (Sandbox Code Playgroud)
设置一下:
n |= mask;
Run Code Online (Sandbox Code Playgroud)
要清楚一点:
n &= ~mask;
Run Code Online (Sandbox Code Playgroud)
要切换一下:
n ^= mask;
Run Code Online (Sandbox Code Playgroud)
请参阅Javascript按位运算符.
UnL*_*oCo 28
我想添加一些东西(感谢@cletus)
function bit_test(num, bit){
return ((num>>bit) % 2 != 0)
}
function bit_set(num, bit){
return num | 1<<bit;
}
function bit_clear(num, bit){
return num & ~(1<<bit);
}
function bit_toggle(num, bit){
return bit_test(num, bit) ? bit_clear(num, bit) : bit_set(num, bit);
}
Run Code Online (Sandbox Code Playgroud)
Ole*_*leb 10
得到一点
function getBit(number, bitPosition) {
return (number & (1 << bitPosition)) === 0 ? 0 : 1;
}
Run Code Online (Sandbox Code Playgroud)
设置位
function setBit(number, bitPosition) {
return number | (1 << bitPosition);
}
Run Code Online (Sandbox Code Playgroud)
清除位
function clearBit(number, bitPosition) {
const mask = ~(1 << bitPosition);
return number & mask;
}
Run Code Online (Sandbox Code Playgroud)
更新位
function updateBit(number, bitPosition, bitValue) {
const bitValueNormalized = bitValue ? 1 : 0;
const clearMask = ~(1 << bitPosition);
return (number & clearMask) | (bitValueNormalized << bitPosition);
}
Run Code Online (Sandbox Code Playgroud)
示例来自JavaScript算法和数据结构存储库.
我在@cletus信息的帮助下构建了一个BitSet类:
function BitSet() {
this.n = 0;
}
BitSet.prototype.set = function(p) {
this.n |= (1 << p);
}
BitSet.prototype.test = function(p) {
return (this.n & (1 << p)) !== 0;
}
BitSet.prototype.clear = function(p) {
this.n &= ~(1 << p);
}
BitSet.prototype.toggle = function(p) {
this.n ^= (1 << p);
}
Run Code Online (Sandbox Code Playgroud)