An Interest In:
Web News this Week
- March 6, 2024
- March 5, 2024
- March 4, 2024
- March 3, 2024
- March 2, 2024
- March 1, 2024
- February 29, 2024
September 25, 2022 02:41 pm GMT
Original Link: https://dev.to/pauljlucas/bit-testing-functions-in-c-5bfi
Bit Testing Functions in C
Introduction
There are many sites giving lots of bit twiddling expressions or functions in C, but none that I've found that give a concise set of bit testing functions, so here is a set I've written. (These are used as part of cdecl.)
The Functions
Does n have either 0 or 1 bits set?
bool is_01_bit( uint64_t n ) { return (n & (n - 1)) == 0;}
Does n have exactly 1 bit set?
bool is_1_bit( uint64_t n ) { return n != 0 && is_01_bit( n );}
Does n have 0 or more bits set that are only among the bits set in set?
bool is_0n_bit_only_in_set( uint64_t n, uint64_t set ) { return (n & set) == n;}
Does n have exactly 1 bit set that is among the bits set in set?
bool is_1_bit_in_set( uint64_t n, uint64_t set ) { return is_1_bit( n & set );}
Note: There may be other bits set in n that are not in set. This function tests only whether exactly 1 of them is in set.
Does n have exactly 1 bit set that is only among the bits set in set?
bool is_1_bit_only_in_set( uint64_t n, uint64_t set ) { return is_1_bit( n ) && is_1_bit_in_set( n, set );}
Is n 0 or have exactly 1 bit set that is only among the bits set in set?
bool is_01_bit_only_in_set( uint64_t n, uint64_t set ) { return n == 0 || is_1_bit_only_in_set( n, set );}
Does n have 1 or more bits set only among the bits set in set?
bool is_1n_bit_only_in_set( uint64_t n, uint64_t set ) { return n != 0 && is_0n_bit_only_in_set( n, set );}
Original Link: https://dev.to/pauljlucas/bit-testing-functions-in-c-5bfi
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To