How to define macro to get bitwidth of a constant?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Henry Yiu

    How to define macro to get bitwidth of a constant?

    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!
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    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.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      There are ways to find the bit-width during execution-time. I'm not aware of any way to do it during compile-time.

      Comment

      • newb16
        Contributor
        • Jul 2008
        • 687

        #4
        Code:
        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.

        Comment

        • Henry Yiu

          #5
          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.

          Comment

          Working...