开发者

Problem when converting from decimal to binary and returning a bitset

I have a strange problem. I have created a simple function to convert from decimal to binary. The argument is a int value that represen开发者_运维技巧ts the number in decimal, and the function returns a bitset that represent the binary number.

The problem is that conversion for a binary number smaller than 10000000000000000000000000000000 (2,147,483,648 in decimal) works perfectly, but when the number to be converted is higher, the conversion doesn't work properly. Where is the mistake???

Here I send you the function:

bitset<15000> Utilities::getDecToBin(int dec)
{
    bitset<15000> columnID; 
 int x;
    for(x=0;x<columnID.size();x++)
    {
       columnID[x]=dec%2;
       dec=dec/2;
    }

    return columnID;
}

Thanks in advance for all your help! :D


The range for an 32 bit int is −2,147,483,648 to 2,147,483,647.

If by larger you mean 1073741825, then I can't see anything wrong.

If you mean adding an extra bit at the most significant position (i.e. 2147483648) then you might be running into signed/unsigned issues.

I see that you restrict your loop by the size of columnID. It would be a good idea to limit it by the size of dec in bits too, or stop when dec is 0.


You should use a long int, an array of long int or even a string as input to your method (depending on the source of your data and how you will call your function).


I am surprised it only works up to 30 bits, you should be able to manage 31 but for 32 bits you would need unsigned ints. If you used unsigned 64-bit integers you could manage a lot more than that, but 15,000-bit integers are something that can only be implemented through special classes.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜