Bia
Bia

Reputation: 183

Converting numbers in binary form and saving them

I need to convert some decimal numbers in binary form and store the strings made of 1s and 0s as rows in a matrix, in C++. Regarding the conversion, I found this simple solution:

std::string binary = std::bitset<8>(128).to_string();

Now, I could simple scan the string and convert each character into a 1 or a 0, filling a matrix's row. Is there a way, a C++ function (or a combo of functions) that allows me to avoid the cost of scanning every bits string?

Thanks for help.

Upvotes: 1

Views: 121

Answers (1)

m.s.
m.s.

Reputation: 16324

There is no need to convert to a std::string first and then convert that to 1/0, you can simply access the bits inside the std::bitset using []:

#include <vector>
#include <bitset>
#include <iostream>

using BitRow = std::bitset<8>;
using BitMatrix = std::vector<BitRow>;

void print(const BitMatrix& bm)
{
    for(const BitRow& row : bm)
    {
        for (std::size_t i=0; i < row.size(); ++i)
        {
            std::cout << row[i] << " ";
        }
        std::cout << std::endl;
    }
}

int main()
{
    BitMatrix bitMatrix;
    bitMatrix.push_back(128);
    bitMatrix.push_back(64);

    print(bitMatrix);
}

live example

Upvotes: 1

Related Questions