Bit Constant Macros in C

Paul J. Lucas
Jun 3, 2023

--

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)

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))

Finally, the greater-than counterparts are trivially:

#define BITS_GT(N)  (~BITS_LE(N))
#define BITS_GE(N) (~BITS_LT(N))

--

--

Paul J. Lucas

C++ Jedi Master. I am NOT available for advice, consultation, recommendations, nor individual training. No, I don't want to write for your publication or site.