Add several bit manipulation functions to C language
[Copy link]
There are instructions in assembly language that operate on bits directly, such as setting, resetting, inverting, testing a certain bit, etc., which are very convenient for hardware operations. Although C language also provides some bit operation methods, such as bitwise AND, bitwise OR, bitwise inversion, etc., they operate on a byte. If you want to operate on a specific bit, it is still inconvenient. The following are some functions that can imitate some bit operation functions of assembly language.
#define uchar unsigned char
/* Test whether a bit of the variable is ' 1 ', return true if it is, otherwise return false, num is the number to be tested, bit is the number of bits, its value ranges from 0 to 7 , the same below */
uchar bittest(uchar num, uchar bit)
{ if(num>>bit&0x01==1)
return 1;
else
return 0;
}
uchar bitclr(uchar num,uchar bit) /* clear a bit */
{
uchar bit_value[]={1,2,4,8,16,32,64,128};
return num&~bit_value[bit];
}
uchar bitset(uchar num,uchar bit) /* Set a bit */
{
uchar bit_value[]={1,2,4,8,16,32,64,128};
return num|bit_value[bit];
}
uchar bitcpl(uchar num,uchar bit) /* Invert a bit */
{
uchar bit_value[]={1,2,4,8,16,32,64,128};
if(num>>bit&0x01==1)
return num&~bit_value[bit];
else
return num|bit_value[bit];
}
/* The following main program demonstrates that when calling, you can directly give a value or a variable name */
void main(void)
{
fly xx=0xfe;
xx=bitset(xx,0);
printf("The set out is %x\n",xx);
printf("The clr out is %x\n",bitclr(255,0));
printf("The test out is %x\n",bittest(0xff,0));
printf("The cpl out is %x\n",bitcpl(0x00,7));
}
The above is the main program written using TC as an example. The functions are also available in other C languages.
|