簡體   English   中英

如何從C中的數字返回多個位

[英]How to return multiple bits from a number in C

我有一個從數字中提取一點的功能:

int getBit (int value, int position) {

    return value & (1 << position));

    }

但是,如何在一定范圍內(帶符號和不帶符號的數字)使用它呢? 例如:

從0x12345678(有符號0)= 0x15獲得位10:14

int getField (int value, int hi, int lo, bool isSigned)

您只需要創建一個蒙版:

int createMask(int a, int b){
int c = a;
int mask = 0;
/*First we set the lenght of the mask*/
while(c <= b){  /*Including b*/
mask <<= 1;
mask = mask|1;
c++;
}
/*Then we set the position to the mask, the first bit is in the position 0*/
c=0;
while(c<a){
c++;
mask <<= 1 ;

}
return mask;
}

我還沒有測試過該功能,但是它只是用於說明制作遮罩的方法。

最后的功能可能是這樣的:

int getBits(int value, int a, int b){
int mask = createMask(a, b);
mask &= value;
//Now we have to move the bits to the right
while(a>0){
mask >>= 1;
a--;
}
return mask;

}

例如,如果要使用前6位,則必須編寫代碼:getBits(myValue,0,5)。

我不確定您對帶符號和無符號數字的意思是什么,但我希望它能為您提供幫助。

對不起,我的英語。

我懷疑您可能想以其他方式解決整個問題。 與其提取位,不如僅使用位掩碼。

例如,要檢查是否啟用了字節中的最高有效位:

if(byte & 0xf0) {}

要檢查最低有效位是:

if(byte & 0x01) {}

要檢查多個(或“范圍”)位,請說低位半字節:

if(byte & 0x0f) {}

根據您所說的,我懷疑這比您想要的要近得多,並且比轉移提取位要簡單得多。

有點有趣:)只需三個簡單步驟:

  1. 經量改變你的價值正確lo ,減少hilo 這簡化了問題“獲得最低位”。

  2. 剪掉最高位-動態創建自定義蒙版。

  3. 如有必要,請使用最高位對結果進行符號擴展(基於從C#中恆定的位寬擴展的Sign進行位糾結)。

我不知道建議使用函數原型的原因,但是我建議使用順序lo, hi而不是hi, lo 從左到右,即使位從高到低倒數,即使以10,14感覺也比其他方法更自然-計算機應該可以使我們更輕松!

#include <stdio.h>
#include <stdbool.h>

int getField (int value, int hi, int lo, bool isSigned)
{
    /* step 1: clip off lower bits */
    value >>= lo;
    hi -= lo-1;
    /* step 2: clip off higher bits */
    value &= ~(-1<<hi);
    /* step 3: extend sign */
    if (isSigned && (value & (1<<(hi-1))))
        value |= -(1<<hi);
    return value;
}

int main (void)
{
    int i;
    i = getField (0x123456c8, 14,10, true);
    printf ("i = %d / %Xh\n", i,i);
    return 0;
}

結果:

i = -11 / FFFFFFF5h

這是正確的位設置:

  16   12    8    4    0 <- bit position
...4    5    6    7    8 <- value
0100 0101 0110 0111 1000 <- bitwise
      --- --             <- mask
      101 01             <- result
 ..111101 01             < sign extended result

暫無
暫無

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

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