簡體   English   中英

單字節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

值為 2^4-2^8 的位

這意味着這個序列:

00000000
00010000
00100000
00110000
...
11110000

或者換句話說,加 16。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM