Home > Mobile >  Binary Strings are Printed Backwards
Binary Strings are Printed Backwards

Time:10-11

I have tried to search for a way to make bit representation of a variable work using macro. The code prints the binary strings backward as I am relatively new to c I thought it was the indexing that was the problem as it needs to start high and then count down.

#include <iostream>
#include <memory>
#include <climits>


#define EXTRACTBIT(ith,ch)(std::cout<<((*ch >> ith) & 1 ? 1 : 0))

template < typename T > void printlnbits (T v)
{
    const int s = sizeof (T) * CHAR_BIT;
    auto const bytes_begining{reinterpret_cast<unsigned char const *>(std::addressof(v))};
    auto byte{bytes_begining};
    auto bit_index_in_byte{0};
    for (int n = s - 1; n >=0; --n)
    {
        EXTRACTBIT(bit_index_in_byte, &(*byte));
          bit_index_in_byte;
        if (CHAR_BIT == bit_index_in_byte){
            std::cout << " ";
            bit_index_in_byte = 0;
              byte;
        }
    }
    std::cout << "  " << s << " bits" << std::endl;
}

int main ()
{
    const char a = 'a';
    const char b = 2;
    printlnbits (a);
    printlnbits (b);

    return 0;
}

Result:

bit_index_in_byte = 0;
  bit_index_in_byte;
10000110  8 bits //correct 01100001
01000000  8 bits //correct 00000010 

bit_index_in_byte = 8;
--bit_index_in_byte;
00110000   8 bits //correct 01100001
00000001   8 bits //correct 00000010

What I have tried has failed, the first one is correct but backward, and the other is incorrect. I would also like to add that any help or other suggestions to simplify the solution would be appreciated

CodePudding user response:

As -500 mentioned in the comment you should have the right result if you start with 7 like this

 auto bit_index_in_byte{7};
    for (int n = s - 1; n >=0; --n)
    {
        EXTRACTBIT(bit_index_in_byte, &(*byte));
        --bit_index_in_byte;
        if (-1 == bit_index_in_byte)
        {
            std::cout << " ";
            bit_index_in_byte = 7;
              byte;
        }
    }`

Result:

01100001 8 bits
00000010 8 bits
  • Related