I was working around with bitset, and so i was wondering what would be the best way to convert a base-10 to base-2, because for some reason i get the wrong answer:
giving the number 19, i’d expect to see:
10011 (16-2-1), why does it output (00011)
#include <iostream>
#include <bitset>
using namespace std;
int main() {
bitset<sizeof(int)> temp(19);
for (int x = 4; x>=0;x--)
cout << temp[x];
cout << endl;
system("pause");
return 0;
}
There were a bug in your code. You can’t access element at index 4 since the size of
bitsetwas 4 due to the fact thatsizeof( int )yielded 4, which only allows accessing from 0-3. As for your question, the template argument within the <> brackets is the size of bitset. In your case, 19 is represented with more than 4 bits, hence the result was truncated. Change the argument to 5, you should get the expected result. By the way,bitsetalready overloaded operator <<, so you don’t actually need to traverse the whole array to output the result.This should do the job: