0

I am a beginner. I am trying to get 2's complement of a binary number which stored in string sou2_reg='000000000000000000000000000000011'. If I will do sou2_reg[32] it gives me 1, the last bit.

Now what I want to do is getting 2's complement of sou2_reg. I tried this but its not working. Can you please give me some piece of code?? Really appreciate

string twosComp(string 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";
     }
}
4

7 回答 7

1

这是使用位操作来避免条件的一种方法。

string twosComp(string number) {
  for (int i = number.length(), carry = 1; i-- > 0;) {
    number[i] = (number[i]^1)+carry; // flip the bit and add the previous carry
    carry = (number[i]&2)>>1;        // save the overflow in the carry variable
    number[i] &= ~2;                 // mask out the overflow 
  }
  return number;
} 
于 2013-05-05T16:47:54.677 回答
1

这可能是一个简单且迭代的实现。

char* complement2(char binaryString[])
{
   int i = 0;
   char *output = (char *)malloc((strlen(binaryString) + 1) * sizeof(char *));

   for(i = 0; binaryString[i] != '\0'; i++)
   {
      output[i] = binaryString[i] ^ 1;
   }
   output[i] = '\0';

   return output;
}
于 2014-07-25T07:17:04.547 回答
1

1)%不适用于字符串

2)您的代码所做的是找到一个的补码。二进制补码就是加一。

std::bitset <MYSIZE> bset(number);
bset.flip(); // one's complement
for (int i = 0; i < bset.size(); i ++) {
    if (bset[i])
        bset[i] = 0;
    else {
        bset[i] = true;
        break;
    }
}
return bset.to_string();
于 2013-05-05T16:16:11.920 回答
1
std::string twos_complement(std::string& number)
{
    for (auto it = number.begin(); it != number.end(); ++it)
    {
        auto& bit = *it;

        bit = (bit == '0') ? '1' : '0';
    }

    //  do adding logic here

    return number;
}
于 2013-05-05T16:22:21.837 回答
0

有关使用 bitset 在 C++ 中表示 2 的恭维的参考:http: //2scomplimentcpp.blogspot.com.au/

于 2014-09-11T01:02:20.167 回答
0

string 是一个数组,您必须单独处理每个位(在您的情况下存储为 char)。对您来说最好的选择是迭代它转换位,并作为最后一步,使用带有进位位的加法进行迭代。想想你将如何在纸上手动完成并使用一串字符将其转换为代码。

于 2013-05-05T16:09:58.283 回答
0
std::string twos_complement(std::string number) {
    bool carry = true;
    for (int i = 0; i < number.size(); ++i) {
        if (!carry)
            number[i] = number[i] == '0' ? '1' : '0';
        else if (number[i] == '0') {
            number[i] = '1';
            carry = false;
        }
    return number;
}
于 2013-05-05T16:40:05.933 回答