二的补码函数的问题

Trouble with a Two's Complement Function

本文关键字:问题 函数 补码      更新时间:2023-10-16

试图实现一个函数来返回一个字符串的二进制补码。我试了两个品种,结果很奇怪。

版本1(进行反转,但不进行"+1"):string twosComp(带符号整数){

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

我一直在尝试这两个函数的各种迭代。我在这件事上没劲了。如果有人有更好的选择的话——在这一点上,我非常愿意接受建议。

(abs(number) ^ 0xffffffff) + 1怎么样,然后将该值转换为字符串?

编辑:为什么是size = 3?int是32位,通常是

下面的代码为一个短(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]='';   // terminate the string
    return s;
}
int main() {
printf("the string is %sn", twosComplement(15)); // just an example
}

为了参考,您可以查看下面的链接,以便在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;
}

您可以使用bitset的to_string()方法将表示转换为字符串。