Home > Blockchain >  How to convert a log2(n) based value to n shifts in a #define statement in C?
How to convert a log2(n) based value to n shifts in a #define statement in C?

Time:04-01

I have a definition of the following type in C:

#define NUM_OF_CHANNELS 8

I want to refer to this definition and use it also for shift operations, such as

a = b >> 3

The value 3 comes from log2(8) = 3.

So I wish there was something like

#define NUM_OF_CHANNELS_SHIFT LOG2(NUM_OF_CHANNELS)
a = b >> NUM_OF_CHANNELS_SHIFT

But obviously the above definition doesn't work. Is there a nifty way to get this accomplished?

CodePudding user response:

Most commonly, you would just do the defines the other way around:

#define NUM_OF_CHANNELS_SHIFT   3
#define NUM_OF_CHANNELS  (1 << NUM_OF_CHANNELS_SHIFT)

This forces you to keep the number of channels a power of two.

CodePudding user response:

Answered by @EricPostpischil in a comment:

If b is known to be nonnegative, simply use b / NUM_OF_CHANNELS. Any decent compiler will optimize it to a shift.

The compiler will translate the following C code into assembly code performing a 3-bit long right-shift.

#define NUM_OF_CHANNELS 8
a = b / NUM_OF_CHANNELS;
  • Related