By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,805 Members | 1,273 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,805 IT Pros & Developers. It's quick & easy.

How to define macro to get bitwidth of a constant?

P: n/a
This is what I am doing now:

#define SIZE 512
#defube SIZE_WIDTH 9

But are there any way to write a preprocessor command to calculate the SIZE_WIDTH from SIZE ? This is what I want to do, but cannot pass compiler:

#define SIZE_WIDTH LOG2(SIZE)

Thanks for any feedback!
Nov 19 '10 #1
Share this Question
Share on Google+
4 Replies


100+
P: 256
I'm not sure if this is a question about preprocessor syntax or implementation detail (or maybe there's an unseen design consideration). The sample code you put up won't compile, so are you confused as to syntax?

There is a log function in math.h and you could use that (and maybe put it in a function rather than a macro).

There are various ways to figure out the position of the highest bit for integer values as well, which may suit your needs (see http://graphics.stanford.edu/~seander/bithacks.html)

You asked for a very specific implementation detail with no surrounding design context. How are you using SIZE_WIDTH (what are you using it to do)? I mean, whats the overall task you're trying to accomplish? Maybe there's a better approach to be taken.
Nov 19 '10 #2

Expert 100+
P: 2,398
There are ways to find the bit-width during execution-time. I'm not aware of any way to do it during compile-time.
Nov 19 '10 #3

100+
P: 687
Expand|Select|Wrap|Line Numbers
  1. void printlog(int left, int right)
  2. {
  3.   if (left==right)
  4.   {
  5.     printf("%d", left);
  6.     return;
  7.   }
  8.   int m = (left+right)/2;
  9.   printf(" ( (i)>=%du)?", 1<<(m+1));
  10.   printlog(m==right?m:m+1,right);
  11.   printf(" : ");
  12.   printlog(left, m); 
  13. }
  14. printlog(0, 5);
  15.  
This will generate something like
( (i)>=8u)? ( (i)>=32u)?5 : ( (i)>=16u)?4 : 3 : .....
that you can define as some #define LOG2(i), and use it at compile time, e.g. for array dimension.
Nov 20 '10 #4

P: n/a
newb16,

What an interesting way to solve a problem!

Yes, this is what I am looking for. I wish the C preprocessor should have included this code to save us from having to generate the code by running another code.
Nov 22 '10 #5

Post your reply

Sign in to post your reply or Sign up for a free account.