Here are some uses of them. These are functions to test, set, and clear bits within a byte.
typedef unsigned char UCHAR;
UCHAR BitSet( UCHAR a, int bit )
{
UCHAR mask = 1 << bit;
return a | mask;
}
UCHAR BitClear( UCHAR a, int bit )
{
UCHAR mask = ~( 1 << bit );
return a & mask;
}
int BitTest( UCHAR a, int bit )
{
UCHAR mask = 1 << bit;
return ( a & mask ) ? 1 : 0;
}
I find that I use these functions most often in code involving communication handling used between devices on ethernet or serial (RS-232 or RS-485) interfaces. The machines my code talks to have a lot of bit-banging in their protocols. These are things like PLCs, LASER scanners, smart cameras, motion controllers, and others using protocols like ModBus, SECS, and proprietary ones.
These functions can be templatized easily by changing
UCHAR
to
T
and adding the
template< typename T >
keywords.