2013-02-11 84 views
0

試圖執行一個函數來返回一串補碼的二進制補碼。我嘗試了兩個品種,並得到奇怪的結果。使用二進制補碼功能時遇到問題

版本1(不反轉而不是 「1」): 串twosComp(signed int的數目){

string twosComp(signed int number) { 

    if (number == 0) { return "1"; } 
    if (number == 1) { return "0"; } 

    if (number % 2 == 0) { 
     return twosComp(number/2) + "1"; 
    } 
    else { 
     return twosComp(number/2) + "0"; 
    } 
} 

版本2(反相併嘗試 「1」,但並不總是得到它的權利)

string twosComp(signed int number) { 

    bool bit = 0; 
    int size = 3; // not sure what to do about this, value could be -32768 to 32767 
    string twos; 
    number = ~abs(number) + 1; 

    for(int i = 0; i < size; i++) { 

     //Get right-most bit 
     bit = number & 1; 
     if(bit) { 
      twos += '1'; 
     } 
     else { 
      twos += '0'; 
     } 

     //Shift all bits right one place 
     number >>= 1; 
    } 

    return twos; 
} // end twosComp 

我一直在嘗試各種這些功能的迭代。我對此一發不可收拾。如果任何人有更好的選擇 - 我非常樂於接受建議。

+0

真的不清楚你的問題是什麼。 – 2013-02-11 03:31:49

+1

如果是這樣,答案是:'〜x + 1' – 2013-02-11 03:33:14

+0

我需要返回位串。 – frankV 2013-02-11 03:34:50

回答

3

(abs(number)^0xffffffff) + 1怎麼樣,然後將該值轉換爲字符串?

編輯:另外,爲什麼是size = 3?整型是32位的,通常

+0

我不知道它是什麼。這是在例子中。我發現它毫無用處。 – frankV 2013-02-11 03:35:48

+0

@frankV它使該函數僅返回給定數字的二進制補碼的最後3位。你給的範圍是16位 – calccrypto 2013-02-11 03:36:37

+0

如果我給一個不同的範圍它會擾亂轉換。我試着「確定」abs(number);產生的二進制數字的字符串「,但那給了我不想要的結果。 – frankV 2013-02-11 03:39:06

0

下面的代碼你想要做什麼的短(16位),INT:說明 - 我用C寫這不是C++ ...

char* twosComplement(signed int n) { 
    static char s[17]; // static so the variable persists after the call 
    unsigned int i; 
    int j; 
    i = (2<<16)-n; // definition of twos complement 

    for(j=0;j<16;j++){ 
     s[15-j] = ((i&1)==0)?'0':'1'; // test lowest bit 
     printf("%c", s[15-j]);  // print for confirmation 
     i=i>>1;      // right shift by one 
    } 
    printf("\n"); // just to make output look clean 
    s[16]='\0'; // terminate the string 
    return s; 
} 

int main() { 
printf("the string is %s\n", twosComplement(15)); // just an example 
} 
0

僅供參考,你可以有++使用位集看看下面鏈接在C語言的整數轉換爲2的補碼: http://2scomplimentcpp.blogspot.com.au/

#include <iostream> 
#include <bitset> 

using namespace std; 

int disp_number() 
{ 
    int i = 0; 
    cout << "Enter Intiger : " ; 
    cin >> i; 
    cout << "decimal : " << std::dec << i << endl; 
    cout << "hex : " << std::hex << i << endl; 
    cout << "oct : " << std::oct << i << endl; 
    cout << "Binary : " << (bitset<16>)i << endl; 
    cout << "Inverse : " << bitset<16>(~i) << endl; 
    i = (0 <= i)?i:(-1)*i; 
    cout << "One's compliment : " << ~(bitset<16>)i << endl; 
    int d = ((bitset<16>)i).flip().to_ulong(); 
    cout << "Two's compliment : " << bitset<16>(++d) << endl; 
    return 0; 
} 

可以使用to_string()位集合的方法的表示形式轉換爲字符串。