读取位并将它们放入整数 [C]

Read bits and put them into integer [C]

我真的是 C 的新手,我在位操作方面遇到了麻烦,我阅读了很多关于它的信息,似乎它是 C 的困难部分之一,有人可以解释我如何收集 32 位然后分配他们到无符号整数。

    unsigned int collect_bits;     // define var
    for (int i = 0;i < 31; i++)    // loop for 32bits
    {
    collect_bits &= HAL_GPIO_ReadPin (GPIOC,GPIO_PIN_9);  //read PORTC current bit and assign it to collect_bits    
    }

我知道上面的代码是错误的,但我不知道如何将位从 PORT 分配给 var

collect_bits未初始化,

试试这个

unsigned int collect_bits = 0;     // define var
for (int i = 0;i < 31; i++)    // loop for 32bits
{
    collect_bits |= HAL_GPIO_ReadPin (GPIOC,GPIO_PIN_9);  //read PORTC status  and assign it to collect_bits    
}

您的代码有 3 个问题:

  • 你没有初始化collect_bits
  • 你的循环只读取 31 位
  • 您在应该使用按位或(又名 |)的地方使用按位与(又名 &)

所以假设 HAL_GPIO_ReadPin return 01,你可以这样做:

unsigned int collect_bits = 0;
for (int i = 0; i < 32; i++)
{
    unsigned int current_bit = HAL_GPIO_ReadPin (GPIOC,GPIO_PIN_9);
    collect_bits |=  current_bit << i;  // Shift current_bit to position i and
                                        // put it into collect_bits using bit wise OR
}

现在从引脚读取的第一个位在 collect_bits 的位位置 0,从引脚读取的第二个位在 collect_bits 的位位置 1,依此类推。

顺便说一句:您必须确保 unsigned int 在您的系统上是 32 位