In assembly language there is direct to the operation of the instructions, such as the position, reset, bit to reverse, test one, etc., this is very convenient for hardware operation, in C language Although also provides some bit manipulation means, such as bitwise AND, bitwise OR, bitwise reverse, but they are to a byte operation, such as to a specific operation, Still inconvenient, the following gives a number of functions, can imitate the assembly language some bit operation function.
#define UCHAR unsigned char
/* Test variable whether one is ' 1 ', is return True, no return false, NUM is to be tested number, bit is the number of digits, its value 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 one/
{
Uchar bit_value[]={1,2,4,8,16,32,64,128};
Return num&~bit_value[bit];
}
Uchar Bitset (uchar num,uchar bit)/* Set a certain one */
{
Uchar bit_value[]={1,2,4,8,16,32,64,128};
return num|bit_value[bit];
}
Uchar bitcpl (uchar num,uchar bit)/* Take the opposite of a
{
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 demo, call, you can directly give the numerical value, also can give the variable name * *
void Main (void)
{
Uchar Xx=0xfe;
Xx=bitset (xx,0);
printf ("The Set is%x/n", XX);
printf ("The CLR out of IS%x/n", BITCLR (255,0));
printf ("The test out of%x/n", Bittest (0xff,0));
printf ("The CPL Out are%x/n", Bitcpl (0x00,7));
}