转换“长”'键入二进制字符串

时间:2015-06-21 08:32:23

标签: c++ string binary data-conversion

我的目标是编写一种能够将长数转换为存储在字符串中的二进制数的算法。

这是我目前的代码块:

#include <iostream>
#define LONG_SIZE 64; // size of a long type is 64 bits

using namespace std;

string b10_to_b2(long x)
{
    string binNum;
    if(x < 0) // determine if the number is negative, a number in two's complement will be neg if its' first bit is zero.
    {
            binNum = "1";
    }
    else
    {
            binNum = "0";
    }
    int i = LONG_SIZE - 1;
    while(i > 0)
    {
            i --;
            if( (x & ( 1 << i) ) == ( 1 << i) )
            {
                    binNum = binNum + "1";
            }
            else
            {
                    binNum = binNum + "0";
            }
    }
    return binNum;
}

int main()
{
    cout << b10_to_b2(10) << endl;
}

该程序的输出是:

00000000000000000000000000000101000000000000000000000000000001010

我希望输出为:

00000000000000000000000000000000000000000000000000000000000001010

任何人都可以发现问题吗?无论出于何种原因,函数输出10由32位表示,而另一位10由32位表示。

2 个答案:

答案 0 :(得分:0)

为什么你认为长64位? 试试const size_t LONG_SIZE=sizeof(long)*8;

检查一下,程序可以正常使用我的更改 http://ideone.com/y3OeB3

编辑:和广告@Mats彼得森指出,您可以通过更改此行来使其更加强大

if( (x & ( 1 << i) ) == ( 1 << i) )

类似

if( (x & ( 1UL << i) ) ) UL很重要,你可以看到他的解释

答案 1 :(得分:0)

几点建议:

  1. 确保使用保证为64位的类型,例如uint64_tint64_tlong long
  2. 为变量i使用上述64位类型,以确保1 << i正确计算。这是因为当移位的位数小于或等于被移位类型中的位数时,移位仅由标准保证 - 1是类型int,对于大多数现代平台(显然包括你的平台)而言是32位。
  3. 不要在#define LONG_SIZE的末尾添加分号 - 或者更好,使用const int long_size = 64;,因为这样可以提供各种更好的行为,例如您在调试器中print long_size print LONG_SIZE 1}}并得到64,其中<Hub Header="this header"> </Hub> 其中LONG_SIZE是一个宏将在调试器中产生错误。