2013-10-15 19 views
1

我試圖從0-130輸出位模式,但不知何故,我只是在相應的位模式應該是顛倒的問號。代碼應該看起來如下所示。有什麼建議麼?C++中的位模式

include <iostream> 
using namespace std; 

int isSet(unsigned int x, int i); 
string bitsetfn(unsigned x, int nbits); 

int main() { 
    for (int counter = 0; counter <=130; counter++){ 
    cout << counter << " is: " << bitsetfn(counter,16)<<endl; 
    } 
    return 0; 
} 

string bitsetfn(unsigned x, int nbits){ 
    string s=" "; 
    for(int j=0; j<nbits; j++) {  
    s+=isSet(x,j); 
    } 
    return s; 
} 

int isSet(unsigned int x, int i) { 
    return ((x >> i) & 1); 
} 

這是輸出應該是什麼樣子......

0 is: 0000000000000000 
1 is: 0000000000000001 
2 is: 0000000000000010 
3 is: 0000000000000011 
4 is: 0000000000000100 
5 is: 0000000000000101 
6 is: 0000000000000110 
7 is: 0000000000000111 
8 is: 0000000000001000 
9 is: 0000000000001001 
10 is:0000000000001010 
11 is: 0000000000001011 
+2

嘗試單曲+ = isSet(X,j)的+ '0';' –

+0

威爾'isSet(X,j)的;'其中j工作> = 8 *的sizeof(x)的? – chux

+0

@RetiredNinja它的作品!你能解釋爲什麼這是可行的嗎?謝謝!! –

回答

2

建議1:您可以使用ostringstream建立你的字符串。

string bitsetfn(unsigned x, int nbits){ 
    ostringstream oss; 
    for(int j=0; j<nbits; j++) {  
    oss << isSet(x,j); 
    } 
    return oss.str(); 
} 

建議2:您可以將二進制數字的整數值轉換爲其等效的字符編碼。在字符編碼的十進制數字被要求是連續的和連續的出發從'0',所以:

s+=isSet(x,j) + '0'; 

將追加任一個'0''1'

建議3:使用bitset

#include <iostream> 
#include <bitset> 
using namespace std; 

int main() { 
    for (int counter = 0; counter <=130; counter++){ 
    cout << counter << " is: " << bitset<16>(counter)<<endl; 
    } 
    return 0; 
}