菜鸟笔记
提升您的技术认知

C语言的getBit,setBit和resetBit位操作函数

C语言getBit, setBit, resetBit程序

  • 使用方便的getBit,setBit,resetBit
  • 位操作函数getBit,setBit,resetBit
    • getBit函数
    • setBit函数
    • resetBit函数
  • 总结

使用方便的getBit,setBit,resetBit

在嵌入式开发过程中,一般采用C语言的编程比较多,但在程序中缺少对位进行操作的函数。所以做了自己的几个函数,可以方便的实现对位的操作。

位操作函数getBit,setBit,resetBit

getBit函数

geiBit函数是用来获取每个位的1或者是0. 程序如下:

bool getBit(word n, word k)
{
  
    bool bx;

    if(((n >> k) & 1) == 1)
        bx = true;
    else
        bx = false;
    return bx;
//    return (n>>(k-1)) & 1;          // shift n with k - 1 bits then and with 1
}

这里要注意的是一般的计算机采用bool来表示二进制变量。但是这个二进制变量也要占用8个位,即一个字节。用getBit函数取出每个位的0或者是1,然后用bool类型的变量来表示这个变量。

setBit函数

setBit函数是用来设置一个变量的特定的位置1. 程序如下:

uint16_t setBit(uint16_t n, int8_t k)
{
  
    uint16_t nx;
    
    nx = 0x1 << k;            // set k bit of nx = 0;
    return n = nx | n;           
}

这个程序先左移k位,然后用这个第k位的1与原来的结果进行与操作,使特定的位保证是1。

resetBit函数

resetBit函数用来将特定的位清零。


uint16_t resetBit(uint16_t n, int8_t k)
{
  
    uint16_t nx;
    
    nx = 0x1 << k;
    nx = ~nx;
    n = n & nx;
    return n;
}

程序先将0x1左移k位,然后取反,再用这个取反的结果与要清零的位相与。

下面的例子程序是一个可以置位和清零位的程序。如果有兴趣的同学还可以读取各个位的结果并在屏幕上输出。

        if(pc.readable())
        {
  
            char cin = pc.getc();
            if( cin == 'c')         // clear k bit of n
            {
  
                pc.printf("Please input the bit you want to clear!\r\n");
                int8_t numbit;
                pc.scanf("%d", &numbit);
                value = clearBit(value, numbit);
                pc.printf("The value now is 0x%4x\r\n", value);
            }
            if( cin == 's')         // clear k bit of n
            {
  
                pc.printf("Please input the bit you want to set!\r\n");
                int8_t numbit;
                pc.scanf("%d", &numbit);
                value = setBit(value, numbit);
                pc.printf("The value now is 0x%4x\r\n", value);
            }            
        }
    }

总结

嵌入式控制器中的C或者是C++程序对位操作是比较少的,可以在开发时自己编辑一下小的程序,也可以制作自己的库方便使用。