[英]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.