Value bits as compile-time constant!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Frederick Gotham

    Value bits as compile-time constant!

    Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
    representing the amount of value representation bits in an unsigned
    integer type. In true C fashion, here it is as a macro:


    /* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 3.2E+
    10 */
    #define IMAX_BITS(m) ((m) /((m)%0x3fffffff L+1) /0x3fffffffL %0x3fffffffL
    *30 \
    + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%
    31+3))


    You supply it with an unsigned integer value whose bit-pattern consists
    of all 1's, e.g.:

    1 (Decimal: 1)
    11 (Decimal: 3)
    111 (Decimal: 7)
    11111111 (Decimal: 255)


    To find out the amount of value bits in an unsigned integer type, you
    supply it with that type's max value (i.e. a bit pattern of all 1's). The
    handiest way to get the max value of an unsigned integer type is to
    assign -1 to it:

    unsigned const max_value = -1;

    unsigned const amount_value_bi ts = IMAX_BITS( max_value );


    Here's some template code I've written which makes use of it:


    template<class T>
    struct IMaxBits {

    template<T m>
    struct AllOnes {

    static unsigned const val =
    m /(m%0x3fffffffL+ 1) /0x3fffffffL %0x3fffffffL *30
    + m%0x3fffffffL /(m%31+1)/31%31*5 + 4-12/(m%31+3);

    };

    };


    template<class T>
    struct AmountValueBits {

    static unsigned const val = IMaxBits<T>::te mplate AllOnes<-1>::val;

    };


    #include <cstdlib>
    #include <cstring>
    #include <cstddef>
    #include <cassert>

    template<std::s ize_t width>
    inline const char* CenterHoriz( const char * const p )
    {
    using std::memset;
    using std::strlen;
    using std::size_t;

    static char spaces[width + 1];


    memset( spaces, ' ', width );

    size_t const len = strlen( p );

    assert( width >= len );


    char * const pos = spaces + ( width / 2 - len / 2 );


    memcpy( pos, p, len );

    return spaces;
    }



    #include <iostream>

    extern char const str_uchar[] = "unsigned char";
    extern char const str_ushort[] = "unsigned short";
    extern char const str_uint[] = "unsigned int";
    extern char const str_ulong[] = "unsigned long";

    template<class T, const char* str>
    void PrintRow()
    {
    using std::cout;

    unsigned const total_bits = sizeof(T) * AmountValueBits <unsigned
    char>::val;
    unsigned const val_bits = AmountValueBits <T>::val;
    unsigned const pad_bits = total_bits - val_bits;

    const char * const spaces_val =
    val_bits > 99 ? "" : ( val_bits > 9 ? " " : " " );

    const char * const spaces_pad =
    pad_bits > 99 ? "" : ( pad_bits > 9 ? " " : " " );

    const char * const spaces_total =
    total_bits > 99 ? "" : ( total_bits > 9 ? " " : " " );


    cout << "||" << CenterHoriz<21> (str) << "|| "
    << spaces_val << val_bits << " || " << spaces_pad <<
    pad_bits
    << " || " << spaces_total << total_bits << " ||\n"

    "---------------------------------------------------------------------
    \n";
    }

    int main()
    {
    using std::cout;

    cout <<

    "
    =============== =============== =============== =\n"
    " || Value bits || Padding Bits || Total Bits
    ||\n"

    "============== =============== =============== =============== ==========
    \n";

    PrintRow<unsign ed char, str_uchar>();
    PrintRow<unsign ed short, str_ushort>();
    PrintRow<unsign ed, str_uint>();
    PrintRow<unsign ed long, str_ulong>();

    cout << "\n\n\n";

    std::system( "PAUSE" );
    }



    I'd be interested to hear if anyone gets some "interestin g" values.



    --

    Frederick Gotham
  • Alf P. Steinbach

    #2
    Re: Value bits as compile-time constant!

    * Frederick Gotham:[color=blue]
    > Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
    > representing the amount of value representation bits in an unsigned
    > integer type. In true C fashion, here it is as a macro:
    >
    >
    > /* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 3.2E+
    > 10 */
    > #define IMAX_BITS(m) ((m) /((m)%0x3fffffff L+1) /0x3fffffffL %0x3fffffffL
    > *30 \
    > + (m)%0x3fffffffL /((m)%31+1)/31%31*5 + 4-12/((m)%
    > 31+3))[/color]

    In C++ you'd use std::numeric_li mits::digits instead.

    --
    A: Because it messes up the order in which people normally read text.
    Q: Why is it such a bad thing?
    A: Top-posting.
    Q: What is the most annoying thing on usenet and in e-mail?

    Comment

    • Howard

      #3
      Re: Value bits as compile-time constant!


      "Frederick Gotham" <fgothamNO@SPAM .com> wrote in message
      news:Xns97EDF3D ACB518fgothamNO SPAM@194.125.13 3.14...[color=blue]
      > Over on comp.lang.c, Hallvard B Furuseth devised a compile-time constant
      > representing the amount of value representation bits in an unsigned
      > integer type. In true C fashion, here it is as a macro:
      >[/color]

      What does this mean: "the amount of value representation bits"?

      -Howard


      Comment

      • Victor Bazarov

        #4
        Re: Value bits as compile-time constant!

        Howard wrote:[color=blue]
        > "Frederick Gotham" <fgothamNO@SPAM .com> wrote in message
        > news:Xns97EDF3D ACB518fgothamNO SPAM@194.125.13 3.14...[color=green]
        >> Over on comp.lang.c, Hallvard B Furuseth devised a compile-time
        >> constant representing the amount of value representation bits in an
        >> unsigned integer type. In true C fashion, here it is as a macro:
        >>[/color]
        >
        > What does this mean: "the amount of value representation bits"?[/color]

        Substitute 'amount' with 'number', does it make it simpler? If not,
        substitue 'value representation' with 'value-representing'. If after
        that it's not clear, then the definition is probably "the number of
        bits involved in representing the value".

        V
        --
        Please remove capital 'A's when replying by e-mail
        I do not respond to top-posted replies, please don't ask


        Comment

        • Frederick Gotham

          #5
          Re: Value bits as compile-time constant!

          Howard posted:

          [color=blue]
          > What does this mean: "the amount of value representation bits"?[/color]


          I'll work off an example.

          Let's say that a byte is 8-Bit, and that sizeof(unsigned short) == 4.

          Therefore, an "unsigned short" takes up 32 bits in memory.

          But that doesn't mean an unsigned short can use 32 bits to store its value.
          It might only use 30 of those bits; the rest are padding bits. The macro
          yields a compile time constant telling us how many bits take part in the
          "value representation" of the unsigned integer type.


          --

          Frederick Gotham

          Comment

          • Howard

            #6
            Re: Value bits as compile-time constant!


            "Frederick Gotham" <fgothamNO@SPAM .com> wrote in message
            news:Xns97EEBC4 75BF87fgothamNO SPAM@194.125.13 3.14...[color=blue]
            > Howard posted:
            >
            >[color=green]
            >> What does this mean: "the amount of value representation bits"?[/color]
            >
            >
            > I'll work off an example.
            >
            > Let's say that a byte is 8-Bit, and that sizeof(unsigned short) == 4.
            >
            > Therefore, an "unsigned short" takes up 32 bits in memory.
            >
            > But that doesn't mean an unsigned short can use 32 bits to store its
            > value.
            > It might only use 30 of those bits; the rest are padding bits. The macro
            > yields a compile time constant telling us how many bits take part in the
            > "value representation" of the unsigned integer type.
            >[/color]

            Interesting. I don't recall ever hearing of padding bits in a stored
            integer before (except perhaps way back in my old 60-bit Cyber mainframe
            days...but those memories are fading). Do any modern machines actually have
            them? All the machines I've worked with in recent years allow you to use
            (for example) all 32 bits of a 32-bit integer. The CPU may contain extra
            "flag" bits, but those don't reduce the amount useable in stored memory.

            -Howard





            Comment

            • Frederick Gotham

              #7
              Re: Value bits as compile-time constant!

              Howard posted:

              [color=blue]
              > Interesting. I don't recall ever hearing of padding bits in a stored
              > integer before (except perhaps way back in my old 60-bit Cyber
              > mainframe days...but those memories are fading).[/color]


              I think super-computers do it, something to do with "emphasizin g
              floating-point arithmetic"...

              [color=blue]
              > All the machines I've worked with in
              > recent years allow you to use (for example) all 32 bits of a 32-bit
              > integer.[/color]


              All the bits in memory belong to you, and they're yours to play around
              with, e.g.:

              unsigned short i;

              unsigned char *p =
              reinterpret_cas t<unsigned char*>( &i );

              unsigned char * const p_over =
              reinterpret_cas t<unsigned char*>( &i + 1 );


              do
              {
              *p++ = 0;
              } while( p != p_over );


              But if you store a value as an unsigned short, then you don't have 2^32
              unqiue values, but rather 2^30... even though it takes up 32 bits in
              memory. It's all about range really:

              0
              through
              ( 2^(amount value bits) ) - 1


              --

              Frederick Gotham

              Comment

              • Howard

                #8
                Re: Value bits as compile-time constant!


                "Frederick Gotham" <fgothamNO@SPAM .com> wrote in message
                news:Xns97EEBF2 C27739fgothamNO SPAM@194.125.13 3.14...[color=blue]
                > Howard posted:
                >
                >[color=green]
                >> Interesting. I don't recall ever hearing of padding bits in a stored
                >> integer before (except perhaps way back in my old 60-bit Cyber
                >> mainframe days...but those memories are fading).[/color]
                >
                >
                > I think super-computers do it, something to do with "emphasizin g
                > floating-point arithmetic"...
                >
                >[color=green]
                >> All the machines I've worked with in
                >> recent years allow you to use (for example) all 32 bits of a 32-bit
                >> integer.[/color]
                >
                >
                > All the bits in memory belong to you, and they're yours to play around
                > with, e.g.:
                >
                > unsigned short i;
                >
                > unsigned char *p =
                > reinterpret_cas t<unsigned char*>( &i );
                >
                > unsigned char * const p_over =
                > reinterpret_cas t<unsigned char*>( &i + 1 );
                >
                >
                > do
                > {
                > *p++ = 0;
                > } while( p != p_over );
                >
                >
                > But if you store a value as an unsigned short, then you don't have 2^32
                > unqiue values, but rather 2^30... even though it takes up 32 bits in
                > memory. It's all about range really:
                >
                > 0
                > through
                > ( 2^(amount value bits) ) - 1
                >[/color]

                (Assuming unsigned short is 30 bits, I guess. On my PC, it's 16 bits, and I
                think on my Mac as well.)

                Thanks,
                -Howard




                Comment

                • Alf P. Steinbach

                  #9
                  Re: Value bits as compile-time constant!

                  * Howard:[color=blue]
                  >
                  > (Assuming unsigned short is 30 bits, I guess. On my PC, it's 16 bits, and I
                  > think on my Mac as well.)[/color]

                  Go back up the thread to find the context for the example.

                  --
                  A: Because it messes up the order in which people normally read text.
                  Q: Why is it such a bad thing?
                  A: Top-posting.
                  Q: What is the most annoying thing on usenet and in e-mail?

                  Comment

                  • Jerry Coffin

                    #10
                    Re: Value bits as compile-time constant!

                    In article <KZUng.62753$mF 2.33728@bgtnsc0 4-
                    news.ops.worldn et.att.net>, alicebt@hotmail .com says...

                    [ ... ]
                    [color=blue]
                    > Interesting. I don't recall ever hearing of padding bits in a stored
                    > integer before (except perhaps way back in my old 60-bit Cyber mainframe
                    > days...[/color]

                    Yup -- 40 significant bits and 20 padding bits.
                    [color=blue]
                    > but those memories are fading).[/color]

                    If you ever want to look at it, _Design of a Computer: The Control
                    Data 6600_, by James Thornton has been scanned in and is available
                    for download a number of places around the 'net. If you're ever
                    struck with a _reallY_ serious bout of nostalgia, check out:

                    the "Desktop Cyber emulator home." It's almost even close to topical,
                    being written in portable C.
                    [color=blue]
                    > Do any modern machines actually have
                    > them? All the machines I've worked with in recent years allow you to use
                    > (for example) all 32 bits of a 32-bit integer. The CPU may contain extra
                    > "flag" bits, but those don't reduce the amount useable in stored memory.[/color]

                    I've seen a compiler for a 12-bit DSP that stored char as 8
                    significant bits with 4 padding bits. That was a few years ago
                    though. In the last few years, DSPs have started to look quite a bit
                    more like mainstream CPUs (while CPUs have started to look a bit more
                    like DSPs).

                    --
                    Later,
                    Jerry.

                    The universe is a figment of its own imagination.

                    Comment

                    • Alf P. Steinbach

                      #11
                      Re: Value bits as compile-time constant!

                      * Jerry Coffin:[color=blue]
                      >
                      > I've seen a compiler for a 12-bit DSP that stored char as 8
                      > significant bits with 4 padding bits.[/color]

                      That would be a non-conforming compiler. For char all bits participate
                      in the value representation. Per the standard.

                      --
                      A: Because it messes up the order in which people normally read text.
                      Q: Why is it such a bad thing?
                      A: Top-posting.
                      Q: What is the most annoying thing on usenet and in e-mail?

                      Comment

                      • Jerry Coffin

                        #12
                        Re: Value bits as compile-time constant!

                        In article <4garpaF1m700kU 1@individual.ne t>, alfps@start.no says...[color=blue]
                        > * Jerry Coffin:[color=green]
                        > >
                        > > I've seen a compiler for a 12-bit DSP that stored char as 8
                        > > significant bits with 4 padding bits.[/color]
                        >
                        > That would be a non-conforming compiler. For char all bits participate
                        > in the value representation. Per the standard.[/color]

                        I should have pointed out that this was a C (89/90) compiler, which
                        didn't have that requirement, if memory serves. OTOH, I'm not sure
                        how conforming code could see the difference, so it might still be
                        able to sneak in under the as-if rule.

                        --
                        Later,
                        Jerry.

                        The universe is a figment of its own imagination.

                        Comment

                        • Frederick Gotham

                          #13
                          Re: Value bits as compile-time constant!

                          Jerry Coffin posted:
                          [color=blue]
                          > In article <4garpaF1m700kU 1@individual.ne t>, alfps@start.no says...[color=green]
                          >> * Jerry Coffin:[color=darkred]
                          >> >
                          >> > I've seen a compiler for a 12-bit DSP that stored char as 8
                          >> > significant bits with 4 padding bits.[/color]
                          >>
                          >> That would be a non-conforming compiler. For char all bits[/color][/color]
                          participate[color=blue][color=green]
                          >> in the value representation. Per the standard.[/color]
                          >
                          > I should have pointed out that this was a C (89/90) compiler, which
                          > didn't have that requirement, if memory serves. OTOH, I'm not sure
                          > how conforming code could see the difference, so it might still be
                          > able to sneak in under the as-if rule.[/color]


                          In C++, only the following three types are guaranteed to contain no
                          padding:

                          char
                          signed char
                          unsigned char


                          In C, only the following type is guaranteed to contain no padding:

                          unsigned char


                          --

                          Frederick Gotham

                          Comment

                          Working...