二进制字符串向后打印

Binary Strings are Printed Backwards

我试图寻找一种方法来使用宏来使变量的位表示起作用。代码向后打印二进制字符串,因为我对 c++ 比较陌生,我认为索引是问题所在,因为它需要从高开始然后向下计数。

#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;
}

结果:

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

我试过都失败了,第一个正确但落后,另一个不正确。我还想补充一点,我们将不胜感激任何帮助或其他简化解决方案的建议

正如评论中提到的 -500,如果你从 7 开始,你应该得到正确的结果

 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;
        }
    }`

结果:

01100001 8 bits
00000010 8 bits