2

How would I change an array of bit sets to a 1d array of ints with each element holding only 1 digit in C++. for example, i have bitset<8> bitArray[n], and I want to bit into int binArray[8*n], where binArray holds something like [0],[1],[1],[0],[1],[0] and so forth.

2 Answers 2

2

You can use an std::bitset::operator[] to access the specifit bit. Keep in mind though, that [0] means the least significant bit, but we want to store them in the most significant -> least significant order, so we have to use the 7 - j instead of simply j:

#include <iostream>
#include <bitset>

int main()
{
    constexpr int SIZE = 5;
    std::bitset<8> bitArray[SIZE] = {3, 8, 125, 40, 13};
    int binArray[8 * SIZE];

    for(int i = 0, index = 0; i < SIZE; ++i){
        for(int j = 0; j < 8; ++j){
            binArray[index++] = bitArray[i][7 - j];
        }
    }
}

The binArrays content looks like so (newlines added by me to improve readability):

0 0 0 0 0 0 1 1
0 0 0 0 1 0 0 0
0 1 1 1 1 1 0 1
0 0 0 0 1 1 0 1
Sign up to request clarification or add additional context in comments.

Comments

0

Simply construct an array:

std::array<int, 8*n> binArray;
size_t out = 0;
for (const auto& bits : bitArray)
    for (size_t ii = 0; ii < n; ++ii)
        binArray[out++] = bitArray[ii];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.