2011-09-28 26 views
0

我想看到編譯二進制負數怎麼寫,所以這裏是代碼應該這樣做補發現算法

#include <cstdlib> 
#include <iostream> 
using namespace std; 
void complement(int n) 
{ 
    int l = n; 
    int s = 0; 
    int k = 0; 
    int m = 0; 

    while (n != 0) 
    { 
     s = n % 2; 
     n /= 2; 
     cout << s << " "; 
    } 

    cout << endl; 
    m = ~l + 1; 
    cout << m << endl; 
    cout << endl; 

    while (m != 0) 
    { 
     int k = m % 2; 
     m /= 2; 
     cout << k << " "; 
    } 
} 

int main(int argc, char *argv[]) 
{ 
    int n; 
    cin >> n; 
    cout << endl; 
    complement(n); 
    system("PAUSE"); 
    return EXIT_SUCCESS; 
} 

,但奇怪的是,當我進入5,例如,其中明確二進制形式是3位101,其補碼-5表示-10-1?這是我的代碼的輸出顯示給我的,但我知道這是不正確的,因爲任意數字的2的補碼是通過反轉它的位,0乘1,反之亦然,然後是+1給出的,如果是5(101 ),-5將是(010 + 1)=(011)。請幫助我,如何糾正我的代碼,以便它可以正確補充。

+5

請正確縮進您的代碼,現在無法讀取。 –

+1

如果您希望得到答案,請在格式化問題時付出一些努力。我縮進了代碼,刪除了一些空行並添加了一些空格,因爲'int k = m%2;'肯定比'int k = m%2;'更好。 – ereOn

回答

1

如果你想看到數位您更好地使用這樣的結構:

int main(int argc, _TCHAR* argv[]) 
{ 
    int i = -10; //my value 
    std::string result; 
    for (int bit = 0; bit < sizeof(int)*8; ++bit) 
    { 
     int bit_val = 1 & i; 
     result = (bit_val ? "1" : "0") + result; 
     i = i >> 1; 
    } 
    std::cout << result << std::endl; 
} 
+0

非常感謝@Jurlie –

+0

對我來說這看起來不正確,因爲循環並不依賴於循環變量...... – themel

+0

作出了更正。現在有用。 @themel我們只需要遍歷數字 – Jurlie

1

看到在C位的最簡單方法++是使用std::bitset。它支持iostream輸出和從字符串轉換。像這樣:

#include <stdio.h>  // printf 
#include <limits.h>  // CHAR_BIT 
#include <bitset> 

int main() 
{ 
    int const bitsPerByte = CHAR_BIT; 
    int const bitsPerInt = sizeof(int)*bitsPerByte; 
    int const m    = -10; 
    std::bitset<bitsPerInt>  bits(m); 

    printf(
     "%d in decimal is %s in %d-bits binary.\n", 
     m, 
     bits.to_string().c_str(), 
     bitsPerInt 
     ); 
} 

輸出:

-10十進制是在32位二進制11111111111111111111111111110110。