std::binary(n)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alex Buell

    std::binary(n)

    Here's something I put together just now; whilst I don't know enough
    to make this act the same way std::hex and std::dec does, this works
    quite well enough for me, but I think I could improve on this.
    Suggestions and flames both welcome. To use, try this:

    unsigned char ch = 0x80;
    std::cout << std::binary(ch) << "\n";

    So, here's the code as follows:

    namespace std
    {
    template <typename _T>
    struct _binary { std::string _digits; };

    template <typename T>
    inline _binary<T> binary(T n)
    {
    _binary<T> __binary;
    int bits = sizeof(n);

    switch (bits)
    {
    case 1 : bits = 7; break;
    case 2 : bits = 15; break;
    case 4 : bits = 31; break;
    // add more if necessary
    }

    for (int i = bits; i >= 0; i--)
    {
    if ((n >> i) & 1)
    __binary._digit s.append("1");
    else
    __binary._digit s.append("0");
    }

    return __binary;
    }

    template <typename T>
    ostream& operator<<(ostr eam& stream, _binary<T> __binary)
    {
    stream << __binary._digit s;
    return stream;
    }
    }


    --


    Take a nap, it saves lives.
  • red floyd

    #2
    Re: std::binary(n)

    Alex Buell wrote:[color=blue]
    > Here's something I put together just now; whilst I don't know enough
    > to make this act the same way std::hex and std::dec does, this works
    > quite well enough for me, but I think I could improve on this.
    > Suggestions and flames both welcome. To use, try this:
    >[/color]
    You mean, other than the fact that you're adding to namespace std and
    using identifiers reserved to the implementation under 17.4.3.1?
    [color=blue]
    > unsigned char ch = 0x80;
    > std::cout << std::binary(ch) << "\n";
    >
    > So, here's the code as follows:
    >
    > namespace std
    > {
    > template <typename _T>
    > struct _binary { std::string _digits; };
    >
    > template <typename T>
    > inline _binary<T> binary(T n)
    > {
    > _binary<T> __binary;
    > int bits = sizeof(n);
    >
    > switch (bits)
    > {
    > case 1 : bits = 7; break;
    > case 2 : bits = 15; break;
    > case 4 : bits = 31; break;
    > // add more if necessary
    > }
    >
    > for (int i = bits; i >= 0; i--)
    > {
    > if ((n >> i) & 1)
    > __binary._digit s.append("1");
    > else
    > __binary._digit s.append("0");
    > }
    >
    > return __binary;
    > }
    >
    > template <typename T>
    > ostream& operator<<(ostr eam& stream, _binary<T> __binary)
    > {
    > stream << __binary._digit s;
    > return stream;
    > }
    > }
    >
    >[/color]

    Comment

    • Alex Buell

      #3
      Re: std::binary(n)

      On Tue, 30 May 2006 23:11:18 GMT, I waved a wand and this message
      magically appeared:
      [color=blue][color=green]
      > > Here's something I put together just now; whilst I don't know enough
      > > to make this act the same way std::hex and std::dec does, this works
      > > quite well enough for me, but I think I could improve on this.
      > > Suggestions and flames both welcome. To use, try this:
      > >[/color]
      > You mean, other than the fact that you're adding to namespace std and
      > using identifiers reserved to the implementation under 17.4.3.1?[/color]

      Good point, guess I should read up on 17.4.3.1.
      --


      Take a nap, it saves lives.

      Comment

      • Alex Buell

        #4
        Re: std::binary(n)

        On Tue, 30 May 2006 23:11:18 GMT, I waved a wand and this message
        magically appeared:
        [color=blue][color=green]
        > > Here's something I put together just now; whilst I don't know enough
        > > to make this act the same way std::hex and std::dec does, this works
        > > quite well enough for me, but I think I could improve on this.
        > > Suggestions and flames both welcome. To use, try this:
        > >[/color]
        > You mean, other than the fact that you're adding to namespace std and
        > using identifiers reserved to the implementation under 17.4.3.1?[/color]

        Umm, in which book and which edition would that be? If it's the C++
        Programming Language book, 17.4.3 only relates to sets.
        --


        Take a nap, it saves lives.

        Comment

        • boaz_sade@yahoo.com

          #5
          Re: std::binary(n)

          Alex Buell wrote:[color=blue]
          > Here's something I put together just now; whilst I don't know enough
          > to make this act the same way std::hex and std::dec does, this works
          > quite well enough for me, but I think I could improve on this.
          > Suggestions and flames both welcome. To use, try this:
          >
          > unsigned char ch = 0x80;
          > std::cout << std::binary(ch) << "\n";
          >
          > So, here's the code as follows:
          >
          > namespace std
          > {
          > template <typename _T>
          > struct _binary { std::string _digits; };
          >
          > template <typename T>
          > inline _binary<T> binary(T n)
          > {
          > _binary<T> __binary;
          > int bits = sizeof(n);
          >
          > switch (bits)
          > {
          > case 1 : bits = 7; break;
          > case 2 : bits = 15; break;
          > case 4 : bits = 31; break;
          > // add more if necessary
          > }
          >
          > for (int i = bits; i >= 0; i--)
          > {
          > if ((n >> i) & 1)
          > __binary._digit s.append("1");
          > else
          > __binary._digit s.append("0");
          > }
          >
          > return __binary;
          > }
          >
          > template <typename T>
          > ostream& operator<<(ostr eam& stream, _binary<T> __binary)
          > {
          > stream << __binary._digit s;
          > return stream;
          > }
          > }
          >
          >
          > --
          > http://www.munted.org.uk
          >
          > Take a nap, it saves lives.[/color]
          " Suggestions and flames both welcome. To use, try this: "
          First do not add something to namespace std - this is only for standard
          libs and your code not yet become part of the standard..
          I think that first you have to consider that there is a standard
          container for this - bitset.
          second there are better ways (speed wise at least) that you can choose
          in implementing this so I think that you have to rethink what you were
          doing..
          good luck anyways and take a nup :)

          Comment

          • Kai-Uwe Bux

            #6
            Re: std::binary(n)

            Alex Buell wrote:
            [color=blue]
            > On Tue, 30 May 2006 23:11:18 GMT, I waved a wand and this message
            > magically appeared:
            >[color=green][color=darkred]
            >> > Here's something I put together just now; whilst I don't know enough
            >> > to make this act the same way std::hex and std::dec does, this works
            >> > quite well enough for me, but I think I could improve on this.
            >> > Suggestions and flames both welcome. To use, try this:
            >> >[/color]
            >> You mean, other than the fact that you're adding to namespace std and
            >> using identifiers reserved to the implementation under 17.4.3.1?[/color]
            >
            > Umm, in which book and which edition would that be? If it's the C++
            > Programming Language book, 17.4.3 only relates to sets.[/color]

            He was refering to the standard itself:

            Adding to namespace std:

            [17.4.3.1/1]
            It is undefined for a C + + program to add declarations or definitions to
            namespace std or namespaces within namespace std unless otherwise
            specified. A program may add template specializations for any standard
            library template to namespace std. Such a specialization (complete or
            partial) of a standard library template results in undefined behavior
            unless the declaration depends on a user-defined name of external linkage
            and unless the specialization meets the standard library requirements for
            the original template.


            Reserved identifiers:

            [17.4.3.1.2/1]
            Certain sets of names and function signatures are always reserved to the
            implementation:
            ? Each name that contains a double underscore (__) or begins with an
            underscore followed by an uppercase letter (2.11) is reserved to the
            implementation for any use.
            ? Each name that begins with an underscore is reserved to the implementation
            for use as a name in the global namespace.


            Best

            Kai-Uwe Bux

            Comment

            • Alex Buell

              #7
              Re: std::binary(n)

              On Wed, 31 May 2006 01:43:50 -0400, I waved a wand and this message
              magically appeared:
              [color=blue][color=green]
              > > Umm, in which book and which edition would that be? If it's the C++
              > > Programming Language book, 17.4.3 only relates to sets.[/color]
              >
              > He was refering to the standard itself:[/color]

              OK, thanks. I've now removed it from std namespace and put it in its
              own namespace. But really we could do with something like std::bin. And
              is there a way to have binary numbers? Something like:

              unsigned char n = 01010101b;

              Would be nice, but I'll make do with hex digits.
              --


              Take a nap, it saves lives.

              Comment

              • Luke Meyers

                #8
                Re: std::binary(n)

                Alex Buell wrote:[color=blue]
                > template <typename _T>[/color]

                Don't use identifiers with leading underscores -- those are reserved.
                [color=blue]
                > struct _binary { std::string _digits; };
                > template <typename T>
                > inline _binary<T> binary(T n)
                > {[/color]

                Umm... why isn't all this work being done in a constructor?
                [color=blue]
                > _binary<T> __binary;
                > int bits = sizeof(n);[/color]

                sizeof returns the size in characters (usu, but not alw, bytes), not
                bits. Seems you already know this, based on your usage in the switch
                statement, but it's a really bad idea to change the semantics of a
                variable midstream like this. It's just confusing and misleading.
                [color=blue]
                > switch (bits)
                > {
                > case 1 : bits = 7; break;
                > case 2 : bits = 15; break;
                > case 4 : bits = 31; break;
                > // add more if necessary
                > }[/color]

                Ever think of making the computer compute this for you? They're good
                at computing stuff. Also, all of these values are off by one, for no
                apparent reason.
                [color=blue]
                >
                > for (int i = bits; i >= 0; i--)[/color]

                Another piece of misleading code -- iterating backwards is unusual, and
                the fact that you're doing it is easy to miss, which could lead to
                unhappy surprises.

                If your bit values weren't off by one, you could just do the far more
                familiar:
                for(int i = 0; i < bits; ++i)
                [color=blue]
                > {
                > if ((n >> i) & 1)[/color]

                And then change this to
                if (n & (1 << i))
                [color=blue]
                > __binary._digit s.append("1");
                > else
                > __binary._digit s.append("0");
                > }[/color]

                I bet single quotes are faster here.
                [color=blue]
                > template <typename T>
                > ostream& operator<<(ostr eam& stream, _binary<T> __binary)[/color]

                Pass by const&, not by value.

                Luke

                Comment

                • Alex Buell

                  #9
                  Re: std::binary(n)

                  On 31 May 2006 08:20:23 -0700, I waved a wand and this message
                  magically appeared:
                  [color=blue]
                  > Don't use identifiers with leading underscores -- those are reserved.[/color]
                  [color=blue]
                  > Umm... why isn't all this work being done in a constructor?[/color]
                  [color=blue]
                  > sizeof returns the size in characters (usu, but not alw, bytes), not
                  > bits. Seems you already know this, based on your usage in the switch
                  > statement, but it's a really bad idea to change the semantics of a
                  > variable midstream like this. It's just confusing and misleading.[/color]
                  [color=blue]
                  > Ever think of making the computer compute this for you? They're good
                  > at computing stuff. Also, all of these values are off by one, for no
                  > apparent reason.[/color]
                  [color=blue]
                  > Another piece of misleading code -- iterating backwards is unusual,
                  > and the fact that you're doing it is easy to miss, which could lead to
                  > unhappy surprises.[/color]
                  [color=blue]
                  > If your bit values weren't off by one, you could just do the far more
                  > familiar:
                  > for(int i = 0; i < bits; ++i)[/color]
                  [color=blue]
                  > And then change this to
                  > if (n & (1 << i))[/color]
                  [color=blue]
                  > I bet single quotes are faster here.[/color]
                  [color=blue]
                  > Pass by const&, not by value.[/color]

                  All this doesn't matter, I've switched to bitsets, as that's a lot
                  easier to work with.
                  --


                  Take a nap, it saves lives.

                  Comment

                  • Marcus Kwok

                    #10
                    Re: std::binary(n)

                    Luke Meyers <n.luke.meyers@ gmail.com> wrote:[color=blue]
                    > sizeof returns the size in characters (usu, but not alw, bytes)[/color]

                    I thought by definition 1 char == 1 byte (though not necessarily
                    1 "octet" or 8 bits).

                    --
                    Marcus Kwok
                    Replace 'invalid' with 'net' to reply

                    Comment

                    • Luke Meyers

                      #11
                      Re: std::binary(n)

                      Marcus Kwok wrote:[color=blue]
                      > Luke Meyers <n.luke.meyers@ gmail.com> wrote:[color=green]
                      > > sizeof returns the size in characters (usu, but not alw, bytes)[/color]
                      >
                      > I thought by definition 1 char == 1 byte (though not necessarily
                      > 1 "octet" or 8 bits).[/color]

                      I think the definition of "byte" is well-established (as 8 bits) and
                      well beyond the jurisdiction of the C++ standard.

                      Luke

                      Comment

                      • Luke Meyers

                        #12
                        Re: std::binary(n)

                        Alex Buell wrote:[color=blue]
                        > On 31 May 2006 08:20:23 -0700, I waved a wand and this message
                        > magically appeared:[/color]

                        Cute, but kind of defeats the purpose -- if you're going to quote me
                        (as you should when replying), I'd appreciate attribution.
                        [color=blue][color=green]
                        > > Umm... why isn't all this work being done in a constructor?[/color]
                        >[color=green]
                        > > Pass by const&, not by value.[/color]
                        >
                        > All this doesn't matter, I've switched to bitsets, as that's a lot
                        > easier to work with.[/color]

                        It's lovely that you've switched to bitsets, but I think I gave you
                        some very useful general C++ tips, so I'm a little dismayed to see you
                        simply assert that it "doesn't matter." Doing construction in
                        constructors, passing by const& to avoid expensive copying, writing
                        clear code, none of this is particular to the problem at hand. It's
                        just stuff you should do when writing C++.

                        Luke

                        Comment

                        • Alf P. Steinbach

                          #13
                          Re: std::binary(n)

                          * Luke Meyers:[color=blue]
                          > Marcus Kwok wrote:[color=green]
                          >> Luke Meyers <n.luke.meyers@ gmail.com> wrote:[color=darkred]
                          >>> sizeof returns the size in characters (usu, but not alw, bytes)[/color]
                          >> I thought by definition 1 char == 1 byte (though not necessarily
                          >> 1 "octet" or 8 bits).[/color]
                          >
                          > I think the definition of "byte" is well-established (as 8 bits) and
                          > well beyond the jurisdiction of the C++ standard.[/color]

                          Nope.

                          Some languages impose 8-bit bytes.

                          C and C++ do not. In the C++ standard, the result of sizeof is defined
                          as the number of bytes, and the size of char is defined as 1 (para
                          5.3.3/1). Which makes char and byte synonyms in C++. By implication,
                          since the C++ standard refers down to the C standard, a C++ byte is at
                          least 8 bits, and in practice all compilers for a given platform use the
                          same byte size. But a byte can be and is larger than 8 bits on some
                          systems, especially in the embedded systems world.

                          --
                          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

                          • Alex Buell

                            #14
                            Re: std::binary(n)

                            On 31 May 2006 16:52:19 -0700, I waved a wand and this message
                            magically appeared from Luke Meyers:
                            [color=blue][color=green]
                            > > All this doesn't matter, I've switched to bitsets, as that's a lot
                            > > easier to work with.[/color]
                            >
                            > It's lovely that you've switched to bitsets, but I think I gave you
                            > some very useful general C++ tips, so I'm a little dismayed to see you
                            > simply assert that it "doesn't matter." Doing construction in
                            > constructors, passing by const& to avoid expensive copying, writing
                            > clear code, none of this is particular to the problem at hand. It's
                            > just stuff you should do when writing C++.[/color]

                            I've kept the file around; I'll work on it when I have the time.
                            --


                            Take a nap, it saves lives.

                            Comment

                            • Alex Buell

                              #15
                              Re: std::binary(n)

                              On 31 May 2006 16:52:19 -0700, I waved a wand and this message
                              magically appeared from Luke Meyers:
                              [color=blue]
                              > It's lovely that you've switched to bitsets, but I think I gave you
                              > some very useful general C++ tips, so I'm a little dismayed to see you
                              > simply assert that it "doesn't matter." Doing construction in
                              > constructors, passing by const& to avoid expensive copying, writing
                              > clear code, none of this is particular to the problem at hand. It's
                              > just stuff you should do when writing C++.[/color]

                              Right, here's my latest binary class:

                              class binary
                              {
                              public:
                              template <typename T>
                              binary(const T& n)
                              {
                              bits = sizeof(n) * 8;
                              for (int i = 0; i < bits; i++)
                              {
                              if (n & (1 << i))
                              digits.insert(d igits.begin(), '1');
                              else
                              digits.insert(d igits.begin(), '0');
                              }

                              if (digits.size() != bits)
                              throw;
                              }

                              friend std::ostream& operator<<(std: :ostream& stream, const
                              binary& bin) {
                              stream << bin.digits;
                              return stream;
                              }

                              private:
                              std::string digits;
                              int bits;
                              };

                              --


                              Take a nap, it saves lives.

                              Comment

                              Working...