简体   繁体   中英

Bitset program C++

I seem to be missing something silly here.

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

Outputs :

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

For a moment i thought it was

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

That just does not change the value of x at all. I am not sure why x is jumping from 2->8->64

Cheers!

You are shifting by i bits every time around the loop.

The first time you shift by 0, keeping the 1. Then you shift by 1, which makes the 1 into a 2. This is then shifted by 2 bits, making it into 8, and so on. Maybe you meant

x = 1 << i;

which would print the value of an integer with successively larger single bits set (1, 2, 4, 8, ...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM