简体   繁体   中英

C++: dynamic_bitset

I'm having trouble initializing my dynamic_bitset . I have this code:

for(int j=(data1.length()-1); j>=0; j--){  
    x[j] = data1[j];  
}

Where data1 is a 32-bit binary number being read in from a file.

When I output the values for data1[j] , it outputs the correct values I need to assign to x, but when I output x (after the supposed initialization), x is all ones.

What am I doing wrong?

EDIT: I'm trying to decompress code. The compressed code is given in lines that are 32 bits long. I want to put everything into one structure for easy access.

My code to initialize x:

int size = numLines * 32; //numLines is the number of lines of 32 bits
boost::dynamic_bitset<> x(size);  

EDIT2:
There are 8 lines of 32-bits each. The for loop is nested within a while loop that accesses each of those 8 lines of 32-bit binary and assignes that value to data1, so data1 changes with every iteration of the while loop.
First iteration:

data1: 10001001110000001001011100110011  

Second iteration:

data1: 00110011001110001010001110000000  

Third iteration:

data1: 00000011100000000000000000000000 

etc....

I want x to be a long bitset containing all those values concatenated with each other.

EDIT3:
Trying one method:

for(int i=0; i<numLines; i++){
    d.append(data1);
}
boost::dynamic_bitset<> x(std::string(d));

See this boost example for how to populate a dynamic_bitset .

Firstly, I would change your loop to:

for (unsigned i = 0; i < data1.length(); i++) {
    x[i] = data1[i];
}

Response to Question Edit:

You can construct a dynamic_bitset using a string :

boost::dynamic_bitset<> x(std::string(data1));

So simply read the whole string in (provided it's not too big), throw away any whitespace so you simply have one long string of 1s and 0s (1001010101101101101110100010...) and then construct your bitset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM