开发者

c++ bitset problem with output

开发者 https://www.devze.com 2023-03-10 19:06 出处:网络
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:

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: givi开发者_开发问答ng 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;
}


sizeof gives a number of char, not a number of bit. sizeof(int) is most probably 4 and thus temp[4] is UB. Use bitset<sizeof(int)*CHAR_BIT>.


You're declaring temp as bitset, where sizeof(int) == 4, so it's declaring a bitset of 4 bits.

The int 19 requires 5 bits.


There were a bug in your code. You can't access element at index 4 since the size of bitset was 4 due to the fact that sizeof( 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, bitset already overloaded operator <<, so you don't actually need to traverse the whole array to output the result. This should do the job:

#include <iostream>
#include <bitset>

using namespace std;

int main() {
    bitset<5> temp(19);
    cout << temp;
    return 0;
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消