2012-03-15 75 views
5

我正在制作机器模拟程序。我有一个主存储器的位集向量,所以我可以使用指向这个向量的指针,pMemory-> at(i)来访问任何特定的“字”。我真的更喜欢bitsets的矢量设计,我坚持它(这个程序是在...约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 >>和<运算符的错误信息?是否真的有必要做所有这些手动争论?

另外,切线方面,当将12位位集复制到16位位集时该怎么办?

谢谢,stackoverflow!这是我对使用Google搜索后的第一个问题。我感谢大家的见解!

+0

+1进行了有益的示范项目。 – 2012-03-15 16:30:57

回答

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

确实在进行颠倒。谢谢你,它编译并按预期运行。 – absterge 2012-03-15 16:43:39

+0

不客气。欢迎来到StackOverflow!不要忘记接受我的回答(点击勾号)。在你完成作业后,四处寻找你**可以回答的问题! – 2012-03-15 16:45:54