431,805 Members | 1,273 Online
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
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 void printlog(int left, int right) {   if (left==right)   {     printf("%d", left);     return;   }   int m = (left+right)/2;   printf(" ( (i)>=%du)?", 1<<(m+1));   printlog(m==right?m:m+1,right);   printf(" : ");   printlog(left, m);  } printlog(0, 5);   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