DEV Community

Paul J. Lucas
Paul J. Lucas

Posted on • Updated on

Bit Constant Macros in C

Introduction

In addition to my bit testing functions in C, here are some bit constant macros in C. (These are used as part of cdecl.)

The Macros

The first macro, given an integer having exactly one bit set, returns a value where all bits less than that are set, e.g., given 0b00010000, returns 0b00001111:

#define BITS_LT(N)  ((N) - 1u)
Enter fullscreen mode Exit fullscreen mode

Given that definition, a macro that returns a value where all bits that are less than or equal to the one set bit is:

#define BITS_LE(N)  (BITS_LT(N) | (N))
Enter fullscreen mode Exit fullscreen mode

Finally, the greater-than counterparts are trivially:

#define BITS_GT(N)  (~BITS_LE(N))
#define BITS_GE(N)  (~BITS_LT(N))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)