Extracting bits from array of ints

I have an array of ints that I need to extract bits from. More specifically, I need to get the high half and the low half of bits of the entire int array.

For example, if I have an array of 9 ints (each one 32 bits), I need to store the first and last 144 bits. I'm likely going to store them as strings.

How can I extract the bits like this?
One way might be to convert them to strings via a bitset (as below).

For an array of ints, just add the strings of bits corresponding to each. Then use the string class's substr() function to grab the first or second half.

First time I've ever used a bitset, I'm afraid, but there seem to be plenty of other options:
http://www.cplusplus.com/reference/bitset/bitset/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
#include <bitset>
using namespace std;

string bits( unsigned int n )
{
   bitset<32> b( n );
   string s = b.to_string<char,string::traits_type,string::allocator_type>();
   return s;
}

int main()
{
   unsigned int n;
   cout << "Enter a positive integer: ";   cin >> n;
   string s = bits( n );
   cout << "Bits: " << s << endl;
}


Enter a positive integer: 65601
Bits: 00000000000000010000000001000001
Topic archived. No new replies allowed.