I'm working on a machine simulation program. I've got a vector of bitsets for main memory, so that I may use a pointer to this vector, pMemory->at(i), to access any specific "word". I really do prefer the vector-of-bitsets design, and I'm sticking with it (this program is due in... about 6 hours, eek!)
I've been having some trouble trying to figure out how to get bitsets in and out of different locations (simulated registers and other memory locations, etc), so I've read up some on using streams. I've come up with this:
#include <bitset>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
/** demonstrating use of stringstream to/from bitset **/
{
bitset<12> sourceBits(std::string("011010010100"));
bitset<12> targetBits(0);
stringstream iBits(stringstream::in | stringstream::out);
iBits << sourceBits.to_string();
cout << targetBits << endl;
iBits >> targetBits;
cout << targetBits << endl;
} //end stringstream to/from bitset
return 0;
}
So, this works, and I can adapt this technique to fit my program.
My questions are, is this a good idea? Is there something fundamental I'm missing about using the bitset >> and << operators? Is it really necessary to do all this manual wrangling?
Also, tangentially, what should I do when copying a 12-bit bitset into a 16-bit bitset?
Thank you, stackoverflow! This is my first question to this community after much googling. I appreciate everyone's insights!
You are overthinking the problem. To copy the value of one bitset to another, use the assignment operator.
#include <iostream>
#include <bitset>
int main () {
std::bitset<12> sourceBits(std::string("011010010100"));
std::bitset<12> targetBits(0);
targetBits = sourceBits;
std::cout << targetBits << "\n";
}
bitset::to_ulong
:
#include <iostream>
#include <bitset>
int main () {
std::bitset<12> sourceBits(std::string("011010010100"));
std::bitset<16> sixteen;
sixteen = sourceBits.to_ulong();
std::cout << sixteen << "\n";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With