簡體   English   中英

將數字聲明為uint32和uint64時,將整數轉換為二進制將顯示不同的輸出

[英]Converting integer to binary shows different outputs when number is declared as uint32 and uint64

我試圖將整數轉換為等效的二進制表示形式。

我正在使用以下算法

void decimal_to_binary(uint32_t number)
{
    char bitset[32];
    for(uint32_t i=0; i<32; ++i)
    {
        if((number & (1 << i)) != 0)
        {
            bitset[31-i] = '1';
        }
        else
        {
            bitset[31-i] = '0';
        }
    }
    for(uint32_t i=0; i<32; ++i)                                                                                                               
    {
        cout << bitset[i];
    }
    cout << "\n";
}

當我針對聲明為uint32_t的實例“ 5”運行此函數時,我得到了正確的結果

decimal_to_binary(5)
00000000000000000000000000000101

但是當我將數字聲明為uint64_t並將位集的大小更改為64位時,結果卻大不相同

添加代碼以執行相同的操作

void decimal_to_binary(uint64_t number)
{
    char bitset[64];
    for(uint64_t i=0; i<64; ++i)
    {
        if((number & (1 << i)) != 0)
        {
            bitset[63-i] = '1';
        }
        else
        {
            bitset[63-i] = '0';
        }
    }
    for(uint64_t i=0; i<64; ++i)
    {
        cout << bitset[i];
    }
    cout << "\n";
}

decimal_to_binary(5)
0000000000000000000000000000010100000000000000000000000000000101

我看到的結果與我在uint32中獲得的結果相同,但將結果並排放置。

這讓我想知道如何以CPP這樣的編程語言實現uint64_t?

我試圖通過查看stdint頭文件來獲得更多詳細信息,但是那里的鏈接確實幫了我很多。

在此先感謝您的時間!!

您的64位代碼中的(1 << i)可能使用1的常規32位int。(默認字長)

因此1被完全移出。 我不明白這如何產生您提供的輸出:)

將1ull用作常數(無符號long long)

問題出在這一行:

if((number & (1 << i)) != 0)

<<運算符的返回類型是左操作數的類型,顯然在您的實現中假定其長度為32位。 將類型移到比其位數總數還遠的位置會產生未定義的行為。

要解決它使用

if((number & (static_cast<uint64_t>(1) << i)) != 0) 

如果僅32位數字,將1移位超過32位是未定義的行為。 未定義的行為意味着它可以執行任何操作。 就像雷蒙德·陳(Raymond Chen)所說的那樣,可能是將右側操作數限制為31(通過按位與32相加)。 這就是為什么要得到64位值下半部分的兩個副本的原因。 嘗試將number向右移動而不是向左移動1

void decimal_to_binary(uint64_t number)
{
    char bitset[64];
    for(size_t i=0; i<64; ++i)
    {
        if(number & 1) != 0)
        {
            bitset[63-i] = '1';
        }
        else
        {
            bitset[63-i] = '0';
        }
        number >>= 1;
    }
    for(size_t i=0; i<64; ++i)
    {
        cout << bitset[i];
    }
    cout << "\n";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM