Search code examples
c++binaryconvertersuint32-t

Quickly Converting uint32_t to binary


The main problem I'm having is to read out values in binary in C++ (python had some really quick/easy functions to do this)

I just need the same. So at the moment I have:

ValWord< uint32_t> data1=//[SOME READ FUNCTION]

When I use cout << data1; It gives me a number e.g 2147581953

I want this to be in binary and eventually each "bit" needs to be in its own bin including all '0's e.g:

for (int i = 31; i >= 0; i--) {
      cout << binary[i];
    }  

Would give me this 32 bit long binary number. When I've had it as a straight forwward int, I've used:

    int data[32];
    bitset<32>(N) = data1;

    for(int i=31; i >=0; i--) {
      data[i]=(bitset<32>(N[i]).to_ulong());
    }

    for (int i = 31; i >= 0; i--) {
      cout << data[i];
    }  

But this just gives me error messages. Any ideas?


Solution

  • Maybe this:

    #define CPlusPlus11 0
    
    #if CPlusPlus11
    int main()
    {
        std::uint32_t value(42);
        std::bitset<32> bits(value);
        std::cout << bits.to_string() << std::endl;
        // Storing integral values in the string:
        for(auto i: bits.to_string(char(0), char(1))) {
            std::cout << (int)i;
        }
        std::cout << std::endl;
        return 0;
    }
    #else
    int main()
    {
        std::uint32_t value(42);
        std::bitset<32> bits(value);
        std::cout << bits.to_string() << std::endl;
        char data[32];
        for(unsigned i = 0; i < 32; ++i) {
            data[i] = bits[i];
        }
        for(unsigned i = 32; i; --i) {
            std::cout << int(data[i-1]);
        }
        std::cout << std::endl;
        return 0;
    }
    #endif
    

    Note: Your expressions bitset<32>(N) = data1 and bitset<32>(N[i]) are code smell.