C 操作位串中的位

C Manipulate Bits Within a Bit String

我目前正在处理一个问题,我试图在位串中操作位。

我正在尝试采用给定的信号掩码:

00101001

并使用 AND 和 OR 运算符根据作为整数给出的信号掩码对其进行检查。

我目前有一些代码接受无符号字符并打印出其二进制表示形式,但我不确定如何继续。

main() {
    int signal = 2;
    unsigned char a = 41;

    int i;
    for (i = 0; i < 8; i++) {
        printf("%d \n", !!((a << i) & 0x80));
    }
    printf("\n");

    return 0;
}

注意:在运行次只检查一个给定的信号编号。

谁能帮我解决这个问题?

如果我对你的问题的解释是正确的,那么你要做的就是在 asignal 之间按位求和:

if ( a & signal ) {
    printf( "Signal bit is set\n" );
} else {
    printf( "Signal bit is not set\n" );
}

对于值 a = 41signal = 2 以上将输出 Signal bit is not set,因为 41 没有在与信号相同的位置设置位。

如果a = 42a = 43它将输出Signal bit is set

如果信号掩码以二进制形式作为字符串提供给程序,您可以使用strtol转换它:

const char *maskstring = "00101001";
unsigned int mask = strtol(maskstring, NULL, 2);

printf("hexmask for binary %s is %#x\n, maskstring, mask);

如果掩码是常量,请自行转换并使用十六进制值。

// input integer with current signal bits
unsigned int signalBits = atoi(signalString);

unsigned int signalOfInterest;
// note signalOfInterest will contain a 'power of 2' value
// such as 1 or 2 or 4 or 8 or 16 or 32 or 64, etc
// which represent the various possible signal bits

// test if signal bit is set
if( signalBits&signalOfInterest )
{ // then signal bit is set

}
else
{ // else, signal bit is not set

}

The purpose of the program is supposed to take the signal number given, set all bits equal to 0 except the number bit that is the signal number and use an AND operator to find out if the signal is set or not based on whether the value is 0 or 1.

您想从信号编号 n 中获取位掩码,这是通过将 1 左移到 nth地方。然后应用一个简单的 &(按位与)来检查该位是否已设置。

int checkSignal(unsigned int value, unsigned char signalNumber){
  unsigned int bitMask = 1 << signalNumber;
  return (value & bitMask) != 0;
}

signalNumber 存储为单个字节,因为 int 位大小不能大于 255;理想情况下,您应该检查它是否不大于 sizeof(int) * 8

请注意,第一个信号位位于索引 0 处,因此根据编号约定,您可能需要将 1 删除到信号编号。

int checkSignal(unsigned int value, unsigned char signalNumber){
  unsigned int bitMask = 1 << (signalNumber - 1); // number starts at 1
  return (value & bitMask) != 0;
}

测试:

main() {
  int signal = 2;
  unsigned char a = 41;

  /*
  int i;
  for (i = 0; i < 8; i++) {
      printf("%d \n", !!((a << i) & 0x80));
  }
  printf("\n");
  */

  printf("%dth bit of %d is %s set\n", signal, a, checkSignal(a, signal)?"":"not"); 

  return 0;

}