首页 文章

两个补语功能的麻烦

提问于
浏览
0

试图实现一个函数来返回一串位的二进制补码 . 我尝试了两个品种并得到奇怪的结果 .

版本1(进行反转但不是“1”):string twosComp(signed int number){

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

我一直在尝试这两种功能的各种迭代 . 我对此已经失去了动力 . 如果有人有更好的选择 - 我现在非常愿意接受建议 .

3 回答

  • 0

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

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

  • 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
    }
    
  • 3

    作为参考,您可以查看以下链接,使用bitset将整数转换为2的C补码: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()方法将表示转换为字符串 .

相关问题