[英]Converting a 'long' type into a binary String
我的目标是编写一种算法,该算法将长整数转换为存储在字符串中的二进制数字。
这是我当前的代码块:
#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
谁能找出问题所在? 无论出于何种原因,该函数输出由32位表示的10与由32位表示的另外10个串联。
您为什么要假设long是64位? 尝试const size_t LONG_SIZE=sizeof(long)*8;
对此进行检查,该程序可以正确执行我的更改http://ideone.com/y3OeB3
编辑:并且广告@Mats Petersson指出您可以通过更改此行使其更强大
if( (x & ( 1 << i) ) == ( 1 << i) )
像
if( (x & ( 1UL << i) ) )
在那个UL很重要的地方,您可以看到他的解释和注释
几点建议:
uint64_t
, int64_t
或long long
。 i
使用上面提到的64位类型,以确保1 << i
计算正确。 这是由于以下事实导致的:仅当移位的位数小于或等于要移位的类型中的位数时,才由标准保证移位-并且1
是int
类型,对于大多数现代平台(显然包括您的)是32位。 #define LONG_SIZE
的末尾加上分号-或者更好的是,使用const int long_size = 64;
因为这样可以提供所有更好的行为,例如,您在调试器中可以print long_size
并得到64,而在其中print LONG_SIZE
其中LONG_SIZE是宏)将在调试器中产生错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.