c++ - bitset 操作的推荐做法是什么?

标签 c++ stream io bitset

我正在研究机器模拟程序。我有一个用于主内存的位集 vector ,因此我可以使用指向该 vector 的指针 pMemory->at(i) 来访问任何特定的“字”。我真的更喜欢位集 vector 设计,并且我坚持使用它(这个程序将在...大约 6 小时内到期,哎呀!)

我在尝试弄清楚如何让位集进出不同位置(模拟寄存器和其他内存位置等)时遇到了一些麻烦,所以我阅读了一些关于使用流的内容。我想出了这个:

#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 >> 和 << 运算符,我缺少一些基本的东西吗?真的有必要进行所有这些手动争论吗?

此外,切线地,将 12 位位集复制到 16 位位集时我应该怎么做?

谢谢你,计算器!这是我在多次 谷歌搜索后向这个社区提出的第一个问题。我感谢大家的见解!

最佳答案

你想多了。要将一个位集的值复制到另一个位集,请使用赋值运算符。

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

关于c++ - bitset 操作的推荐做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9723584/

相关文章:

c++ - 对象数组的默认复制行为

node.js - Node流中的结束和完成事件有什么区别

c++ - C++ 流中的eof()、fail()、bad() 和good() 之间有什么区别?

c++ - 将管道与字符串数组一起使用

c++ - 使用 WinCrypt/CryptoAPI 验证基于 OpenPGP 的 RSA 签名

c++ - 来自 tcmalloc 的意外行为

java - ObjectInputStream 和 getInputStream

java - 在网络摄像头流上读取和写入

c - 原始硬盘访问/dev/sda] vs/dev/sg[y]?

c++ - 如果输入错误则无限循环