2017-07-04 110 views
-3

我有一個字節數組表示爲位運算和int

char * bytes = getbytes(object); //some api function 

我想檢查在一些位置x處的位是否被設置。

我一直想這個

int mask = 1 << x % 8; 
y= bytes[x>>3] & mask; 

然而Ÿ收益都爲零?我做錯了什麼,是否有更簡單的方法來檢查是否設置了一點?

編輯:

我也運行此。它也沒有以預期的結果返回。

int k = x >> 3; 
    int mask = x % 8; 
    unsigned char byte = bytes[k]; 
    return (byte & mask); 

它失敗了一個斷言真正的ctest我跑了。字節和掩碼此時分別從「gdb」打印「0002」和2。

編輯2:這是我如何設置位的第一位。我只是想寫一個測試來驗證它們是否已設置。

unsigned long x = somehash(void* a);

unsigned int mask = 1 << (x % 8);

unsigned int location = x >> 3; 
char* filter = getData(ref); 

filter[location] |= mask; 
+1

括號'()'是你的朋友。 – Yunnosch

+0

表達對我來說很好。 'y'的類型是什麼? 'bytes'指向'char'的連續內存區域嗎? – nglee

+0

混淆的一個可能的來源是位端。現在,您的代碼將「x = 0」解釋爲第一個字節的最低有效位。 – user3386109

回答

0

這將是一個(粗也許)從我的頭頂方式:

#include "stdio.h" 
#include "stdlib.h" 

// this function *changes* the byte array 
int getBit(char *b, int bit) 
{ 
    int bitToCheck = bit % 8; 
    b = b + (bitToCheck ? (bit/8) : (bit/8 - 1)); 

    if (bitToCheck) 
    *b = (*b) >> (8 - bitToCheck); 

    return (*b) & 1; 
} 

int main(void) 
{ 
    char *bytes = calloc(2, 1); 
    *(bytes + 1)= 5; // writing to the appropiate bits 
    printf("%d\n", getBit(bytes, 16)); // checking the 16th bit from the left 
    return 0; 
} 

假設:

一個字節表示如:

---------------------------------------- 
| 2^7 | 2^6 | 2^5 | 2^4 | 2^3 |...  | 
---------------------------------------- 

最左邊的位被認爲是位數1,最右邊的位被認爲是最大的位。編號位(2字節對象中的第16位)。

可以覆蓋實際的byte對象(如果不需要,請使用memcpy)。

+0

我認爲你必須考慮系統的endiannes像[here](https:/ /stackoverflow.com/a/4181991/8051589),因爲您在一個數組中有多個字節。 –

+0

你們知道嗎。我認爲這可能與bool typedef和我用來檢索字節的api有關。我做了一切香草整齊,它似乎按預期運行。我打算進一步研究它,並與原作者 – knowads

+0

@AndreKampling Ahhh討論......你只需要讓我覺得這很困難; P – babon