Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's recommended practice for bitset manipulation?

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!

like image 368
absterge Avatar asked Mar 15 '12 16:03

absterge


1 Answers

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";
}


Your tangential question is answered by 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";
}
like image 59
Robᵩ Avatar answered Oct 10 '22 05:10

Robᵩ