C 字节和整数的位运算

C 字节和整数的位运算,c,bit-manipulation,bitwise-operators,bit,C,Bit Manipulation,Bitwise Operators,Bit,我有一个字节数组,表示为 char * bytes = getbytes(object); //some api function 我想检查是否设置了某个位置x的位 我一直在试这个 int mask = 1 << x % 8; y= bytes[x>>3] & mask; 我运行的断言真实ctest失败。此时的字节和掩码,其中从gdb打印时分别为“0002”和“2” 编辑2:这是我首先设置位的方式。我只是想写一个测试来验证它们是否设置好了 无符号长x=some

我有一个字节数组,表示为

char * bytes = getbytes(object); //some api function
我想检查是否设置了某个位置x的位

我一直在试这个

int mask = 1 << x % 8;
y= bytes[x>>3] & mask;
我运行的断言真实ctest失败。此时的字节和掩码,其中从gdb打印时分别为“0002”和“2”

编辑2:这是我首先设置位的方式。我只是想写一个测试来验证它们是否设置好了

无符号长x=somehash(void*a)

unsigned int mask=1这可能是我头顶的一个(粗糙的)方式:

#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位)


可以覆盖实际的
字节
对象(如果不需要,请使用
memcpy
)。

括号
()
是您的朋友。我觉得这个表达式不错。
y
的类型是什么?
bytes
是否指向
char
s的连续内存区域?一个可能的混淆源是位端性。也就是说,你的代码解释<代码> x=0 < /代码>作为第一字节的最低有效位。请提供示例输入和预期输出。简而言之,请制作A。我想你必须考虑系统的EndiaNes,因为你在数组中有多个字节。你们知道吗?我认为这可能与booltypedef和我用来检索字节的api有关。我做了所有的香草ints,它看起来像预期的那样运行。我将进一步研究它,并与原文进行讨论author@AndreKampling啊。。。你只是让我很难受;P@knowads“无事生非”?@babon我想是的。我还没有意识到我可以完全正确,但由于某人的原始API中的实现决策没有考虑某些用例,所以可能会出现一些错误
#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 |...     |
----------------------------------------