2013-02-11 49 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()位集合的方法的表示形式转换为字符串。