Search code examples
c++arraysbitset

converting a bitset array to array of ints


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.


Solution

  • 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