2017-07-04 50 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