Reputation: 693
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
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
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-1
th bit.
Upvotes: 0