如何在JavaScript中设置,清除和切换一个位?
答
为了得到一个位掩码:
var mask = 1 << 5; // gets the 6th bit
为了测试某个位设置:
if ((n & mask) != 0) {
// bit is set
} else {
// bit is not set
}
要设置位:
n |= mask;
要清除位:
n &= ~mask;
要切换了一下:
n ^= mask;
答
我想添加一些东西(与感谢@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的帮助信息:
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);
}
@user JavaScript和C/C++是不同的语言。非常有帮助,他们都有不同的答案。 – cmac 2017-03-09 20:00:33