DEV Community

Paul J. Lucas
Paul J. Lucas

Posted on • Updated on

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 exactly 1 bits set?

bool is_01_bit( uint64_t n ) {
  return (n & (n - 1)) == 0;
}
Enter fullscreen mode Exit fullscreen mode

Does n have exactly 1 bit set?

bool is_1_bit( uint64_t n ) {
  return n != 0 && is_01_bit( n );
}
Enter fullscreen mode Exit fullscreen mode

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 );
}
Enter fullscreen mode Exit fullscreen mode

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 );
}
Enter fullscreen mode Exit fullscreen mode

Does n have either 0 or 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 );
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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 );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)