Search code examples
c++bitsetstd-bitset

How to access range of bits in a bitset?


I have a bitset which is very large, say, 10 billion bits.

What I'd like to do is write this to a file. However using .to_string() actually freezes my computer.

What I'd like to do is iterate over the bits and take 64 bits at a time, turn it into a uint64 and then write it to a file.

However I'm not aware how to access different ranges of the bitset. How would I do that? I am new to c++ and wasn't sure how to access the underlying bitset::reference so please provide an example for an answer.

I tried using a pointer but did not get what I expected. Here's an example of what I'm trying so far.

#include <iostream>
#include <bitset>
#include <cstring>
using namespace std;

int main()
{
    bitset<50> bit_array(302332342342342323);
    cout<<bit_array << "\n";
    bitset<50>* p;
    p = &bit_array;
    p++;
    int some_int;
    memcpy(&some_int, p , 2);
    cout << &bit_array << "\n";
    cout << &p << "\n";
    cout << some_int << "\n";

    return 0;
}

the output

10000110011010100111011101011011010101011010110011
0x7ffe8aa2b090                                                                                                                          
0x7ffe8aa2b098
17736

The last number seems to change on each run which is not what I expect.


Solution

  • There are a couple of errors in the program. The maximum value bitset<50> can hold is 1125899906842623 and this is much less than what bit_array has been initialized with in the program.

    some_int has to be defined as unsigned long and verify if unsigned long has 64 bits on your platform.

    After this, test each bit of bit_array in a loop and then do the appropriate bitwise (OR and shift) operations and store the result into some_int.

    std::size_t start_bit = 0;
    std::size_t end_bit = 64;
    for (std::size_t i = start_bit; i < end_bit; i++) {
        if (bit_array[i])
           some_int |= mask;
        mask <<= 1;
    }
    

    You can change the values of start_bit and end_bit appropriately as you navigate through the large bitset.

    See DEMO.