2011-02-01 41 views
1

我似乎在這裏錯過了一些愚蠢的東西。Bitset程序C++

int main() 
{ 
     /* 
     bitset<sizeof(int)*8> bisetInt(64); 
     cout<<"Sizeof is "<<sizeof(int)<<endl; 

     for(int i=0;i< sizeof(int)*8;i++) 
       cout<<bisetInt[i]<<endl; 
     //cout<<"no bits set are "<<bisetInt.count()<<endl; 
     */ 

     int num = 5; 
     int x = 1; 


     for (int i = 0;i < 5; i++) 
     {   
       x = x<<i; 
       cout<< (num & x)<<endl; 
       cout<<"value of x is "<<x<<endl; 
     } 

     return 0; 
} 

輸出:

1 
value of x is 1 
0 
value of x is 2 
0 
value of x is 8 
0 
value of x is 64 
0 
value of x is 1024 

對於一個時刻,我認爲這是

x = x<<i; //not this 
x<<i;//rather this 

這只是不會改變x的值在所有。我不知道爲什麼x從2-> 8-> 64跳轉

乾杯!

回答

5

您每循環移動i位。

第一次移動0,保持1.然後你移動1,這會使1變成2.然後移動2位,使它變成8,依此類推。也許你的意思是

x = 1 << i; 

這將打印一個整數的值連續更大的單個位集(1,2,4,8,...)。

+0

Doh!謝謝 :) – 2011-02-01 15:42:40