你如何设置,清除和切换JavaScript中的一个位?
如何在JavaScript中设置,清除,切换和检查一下?
得到一个掩码:
var mask = 1 << 5; // gets the 6th bit 要testing是否设置了一点:
 if ((n & mask) != 0) { // bit is set } else { // bit is not set } 
设置一下:
 n |= mask; 
要清楚一点:
 n &= ~mask; 
切换一下:
 n ^= mask; 
请参阅Javascript按位运算符 。
我想添加一些东西(感谢@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); } 
我在@cletus信息的帮助下构build了一个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); }