write binary representation to output

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • wongjoekmeu@yahoo.com

    write binary representation to output

    Dear all,
    I was wondering how in C++ the code would look like if I want to write
    the binary notation of a unsigned char to standard output or any other
    basic data type, like int, unsigned int, float and so forth.
    Thanks in advance.
    RR
  • Juha Nieminen

    #2
    Re: write binary representation to output

    wongjoekmeu@yah oo.com wrote:
    I was wondering how in C++ the code would look like if I want to write
    the binary notation of a unsigned char to standard output or any other
    basic data type, like int, unsigned int, float and so forth.
    #include <iostream>
    #include <climits>

    template<typena me Type>
    void printBinaryRepr esentation(cons t Type& value)
    {
    // Resolve if this is a big-endian or a little-endian system:
    int dummy = 1;
    bool littleEndian = (*reinterpret_c ast<char*>(&dum my) == 1);

    // The trick is to create a char pointer to the value:
    const unsigned char* bytePtr =
    reinterpret_cas t<const unsigned char*>(&value);

    // Loop over the bytes in the value:
    for(unsigned i = 0; i < sizeof(Type); ++i)
    {
    unsigned char byte;
    if(littleEndian ) // we have to traverse the value backwards:
    byte = bytePtr[sizeof(Type) - i - 1];
    else // we have to traverse it forwards:
    byte = bytePtr[i];

    // Print the bits in the byte:
    for(int bitIndex = CHAR_BIT-1; bitIndex >= 0; --bitIndex)
    {
    std::cout << ((byte >bitIndex) & 1);
    }
    }

    std::cout << std::endl;
    }

    Comment

    • Alf P. Steinbach

      #3
      Re: write binary representation to output

      * wongjoekmeu@yah oo.com:
      >
      I was wondering how in C++ the code would look like if I want to write
      the binary notation of a unsigned char to standard output or any other
      basic data type, like int, unsigned int, float and so forth.
      E.g.

      <code>
      #include <iostream // std::cout, std::ostream
      #include <ostream // operator<<, std::endl
      #include <bitset // std::bits
      #include <climits // CHAR_BIT

      static unsigned const bitsPerByte = CHAR_BIT;

      template< typename T >
      struct BitSize
      {
      enum { value = bitsPerByte*siz eof( T ) };
      };

      template< typename T >
      std::bitset< BitSize<T>::val ue bitsetFrom( T const& v )
      {
      typedef std::bitset< BitSize<T>::val ue BitSet;

      BitSet result;
      unsigned char const* p = reinterpret_cas t<unsigned char const*>( & v );

      // Uses little-endian convention for bit numbering.
      for( size_t i = sizeof(T)-1; i != size_t(-1); --i )
      {
      result <<= bitsPerByte;
      result |= BitSet( p[i] );
      }
      return result;
      }

      int main()
      {
      using namespace std;

      int const i = 1234;
      float const f = 1234.567;

      cout << bitsetFrom( i ) << endl;
      cout << bitsetFrom( f ) << endl;
      }
      </code>


      Cheers, & hth,.

      - Alf

      Comment

      • James Kanze

        #4
        Re: write binary representation to output

        On 19 avr, 10:19, Juha Nieminen <nos...@thanks. invalidwrote:
        wongjoek...@yah oo.com wrote:
        I was wondering how in C++ the code would look like if I
        want to write the binary notation of a unsigned char to
        standard output or any other basic data type, like int,
        unsigned int, float and so forth.
        #include <iostream>
        #include <climits>
        template<typena me Type>
        void printBinaryRepr esentation(cons t Type& value)
        {
        // Resolve if this is a big-endian or a little-endian system:
        int dummy = 1;
        bool littleEndian = (*reinterpret_c ast<char*>(&dum my) == 1);
        And what about middle endian? If a type has more than two
        bytes, then more than two orders are possible, and in fact, I've
        seen at least three for long (on very common machines, no less).

        For the rest, I don't think that this is what he was looking
        for, and even if it was, I don't see any reason to access byte
        by byte.

        --
        James Kanze (GABI Software) email:james.kan ze@gmail.com
        Conseils en informatique orientée objet/
        Beratung in objektorientier ter Datenverarbeitu ng
        9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

        Comment

        • Juha Nieminen

          #5
          Re: write binary representation to output

          James Kanze wrote:
          And what about middle endian?
          Most probably we can ignore obscure architectures.
          For the rest, I don't think that this is what he was looking
          for, and even if it was, I don't see any reason to access byte
          by byte.
          How else? The size of the type will be n bytes, so accessing byte by
          byte is the most logical choice. How else would you do it?

          Comment

          • Charles Coldwell

            #6
            Re: write binary representation to output

            "wongjoekmeu@ya hoo.com" <wongjoekmeu@ya hoo.comwrites:
            Dear all,
            I was wondering how in C++ the code would look like if I want to write
            the binary notation of a unsigned char to standard output or any other
            basic data type, like int, unsigned int, float and so forth.
            Thanks in advance.
            RR
            How about this:

            #include <iostream>
            #include <iomanip>

            template<typena me Tstruct binary_traits
            {
            typedef T int_t;
            };

            template<struct binary_traits<f loat>
            {
            typedef int int_t;
            };

            template<struct binary_traits<d ouble>
            {
            typedef long long int_t;
            };

            template<typena me T>
            void output(T x)
            {
            std::cout << std::setw(sizeo f(x)*2) << std::setfill('0 ') << std::hex
            << * reinterpret_cas t<typename binary_traits<T >::int_t *>(&x)
            << std::endl;
            }

            int main(int argc, char *argv[])
            {
            output(10);
            output(10L);
            output(10LL);
            output(0.1f);
            output(0.1);

            return 0;
            }



            --
            Charles M. "Chip" Coldwell
            "Turn on, log in, tune out"
            GPG Key ID: 852E052F
            GPG Key Fingerprint: 77E5 2B51 4907 F08A 7E92 DE80 AFA9 9A8F 852E 052F

            Comment

            • James Kanze

              #7
              Re: write binary representation to output

              On 20 avr, 11:41, Juha Nieminen <nos...@thanks. invalidwrote:
              James Kanze wrote:
              And what about middle endian?
              Most probably we can ignore obscure architectures.
              That was a Microsoft compiler, on an Intel architecture. I
              don't know that the word "obscure" is appropriate in such cases.
              For the rest, I don't think that this is what he was looking
              for, and even if it was, I don't see any reason to access byte
              by byte.
              How else? The size of the type will be n bytes, so accessing
              byte by byte is the most logical choice. How else would you do
              it?
              As itself?

              --
              James Kanze (GABI Software) email:james.kan ze@gmail.com
              Conseils en informatique orientée objet/
              Beratung in objektorientier ter Datenverarbeitu ng
              9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

              Comment

              • Juha Nieminen

                #8
                Re: write binary representation to output

                James Kanze wrote:
                >>For the rest, I don't think that this is what he was looking
                >>for, and even if it was, I don't see any reason to access byte
                >>by byte.
                >
                >How else? The size of the type will be n bytes, so accessing
                >byte by byte is the most logical choice. How else would you do
                >it?
                >
                As itself?
                How do you access individual bits of a double? (Or a struct containing
                several member variables, for example.)

                Comment

                Working...