推荐的bitset操作实践是什么?

时间:2012-03-15 16:04:32

标签: c++ stream io bitset

我正在研究机器模拟程序。我有一个主存储器的位集向量,因此我可以使用指向此向量的指针,pMemory-> at(i)来访问任何特定的“单词”。我真的更喜欢矢量的位组设计,而且我坚持使用它(这个程序应该在...大约6个小时,eek!)

我一直在努力弄清楚如何在不同的位置(模拟寄存器和其他内存位置等)进出bitset,所以我已经阅读了一些关于使用流的信息。我想出了这个:

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

所以,这是有效的,我可以调整这种技术以适合我的程序。

我的问题是,这是一个好主意吗?我是否缺少使用bitset&gt;&gt;的基本功能?和&lt;&lt;运营商?是否真的有必要进行所有这些手动争论?

另外,切向地说,将12位bitset复制到16位bitset时该怎么办?

谢谢,stackoverflow!在很多谷歌搜索之后,这是我对这个社区的第一个问题。我感谢大家的见解!

1 个答案:

答案 0 :(得分:9)

你正在过度思考这个问题。要将一个bitset的值复制到另一个bitset,请使用赋值运算符。

#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";
}
相关问题