2011-02-01 82 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