randomUser
randomUser

Reputation: 693

Can some explain the logic for this output?

I am printing a string (created by bitset in stl) and then printing the string directly and by using loop why there is difference in the output?

#include<iostream>
#include<bitset>
using namespace std;
int main()
{
    const int m=16;
    int n;
    int arr[m];
        cin>>n;
        bitset<m>bt(n);
        cout<<bt<<endl;
        for(int i=0;i<m;i++)
        {
            cout<<bt[i];
        }
}

Input:
995

Output:
0000001111100011 //Printing string
1100011111000000 //Printing using loop

The output of one is reverse the other .
I do not understand why this is happening?

Upvotes: 0

Views: 72

Answers (2)

Jugal Rawlani
Jugal Rawlani

Reputation: 157

cout << bt << endl;

The above prints the number as desired

cout << bt[0] << endl;

however, when we index a bitmap, the indexing starts from the rightmost bit, or the LSB.

As quoted on http://www.cplusplus.com/reference/bitset/bitset/operator[]/

Order positions are counted from the rightmost bit, which is order position 0.

Upvotes: 1

vtronko
vtronko

Reputation: 488

It is consistent with the way bits are usually numbered, [0] represents the LSB(least significant bit). When you convert bitset to string — it will contain bits the opposite order, with first character corresponding to N-1th bit.

Upvotes: 0

Related Questions