单个字节的按位计数器 javascript

bit wise counter on a single byte javascript

我想在 Typed 16Uint 数组项中使用值为 2^4-2^8 的位作为 16 的二进制计数器。

0000111100000000 ->15
0000111000000000 ->14
0000110100000000 ->13
...
0000000000000000 ->0

有没有简单的位运算可以用二进制计算? 我目前的策略是提取位作为数字加一 - 做一些错误检查,然后用 a&0 设置原始位并用 | 或掩码替换该部分?

cellBinary = iterate(cellBinary, 16, 4);
function iterate(cellBinary, start, length)
    {
    let number = extractBits(cellBinary, start, length);
    if(number < 15)
        {
        number++;
    }
    what = eraseIterator(what);
    what = what|number;
    return what;
}
function extractBits(what, start, length)
    {
    return ((1 << start ) -1) & (what >> (length - 1));
}
function eraseIterator(what)
    {
    what&16^1; //also iffy if this will work as intended.
    what&32^1; //this is supposed to set 16-128 to 0.
    what&64^1;
    what&128^1; 
    return what;
}

有没有更好的方法来完成这个? 注意:代码是一个例子,我正在寻找一个策略,而不是一个错误。

你可以直接加上合适的数量:256,二进制100000000。

例如,

000000000000 + 100000000 ->
000100000000
001000000000
001100000000
...
111100000000

the bits valued at 2^4-2^8

这意味着这个序列:

00000000
00010000
00100000
00110000
...
11110000

或者换句话说,加16。