如何将二进制数组转换为2的补码?

时间:2015-10-09 16:01:38

标签: c arrays twos-complement

我在尝试转换为2补码方面遇到了麻烦。我知道问题是什么,但我无法弄清楚如何解决它。 问题是内部for循环中的两个if语句,因为一个将值更改为0,然后另一个将其更改回1.我尝试将其更改为if和else if if但是它的值变得更糟。

/*
 Signed array[] contains digits of 0 or 1 and at index 0 of the array
 is where it is determined positive or negative. the parameter size is
 the number of digits. Returns the 2's complement of the given array
 with the same number of digits (size of array).
 */

int* signed2Complement2(int signed_binary[], int size){

   int i, j, k;

   int negative = 1;

   int size2 = size;

   int begin_of_array = 0;

   int complement_binary[size];

   if(signed_binary[begin_of_array] == 0){

      negative = 0;

      printf("Is positive %d\n", negative);

   }

   else printf("Is negative %d\n", negative);


   for(i = size-1; i>=0; i--){

       complement_binary[i] = signed_binary[i];

       printf("Binary at %d is: %d\n", i, complement_binary[i]);

   }

   for(j = size2 -1; j>=0; j--){

       if(complement_binary[j] == 1){

          for(k = j; k>=0;k--){

                if(complement_binary[k] == 1){

                complement_binary[k] = 0;

                printf("Binary at %d is: %d\n", k, complement_binary[k]);

             }

             if(complement_binary[k] == 0){

                complement_binary[k] = 1;

                printf("Binary at %d is: %d\n", k, complement_binary[k]);

             }

          }

       }

    }



return complement_binary;

}

1 个答案:

答案 0 :(得分:2)

我觉得你很困惑我的朋友。要计算二进制数的二进制补码,有两步:

1.取一个人的补充。

2.将1添加到一个补码。

所以我的c代码是:

int* signed2Complement2(int signed_binary[], int size)
    {
       int i, j, k;
       int negative = 1;
       int size2 = size;
       int begin_of_array = 0;
       int *complement_arr=malloc(size*sizeof(int));
       if(signed_binary[begin_of_array] == 0){
          negative = 0;
          printf("Is positive %d\n", negative);
       }
       else printf("Is negative %d\n", negative);
       for(i=size-1;i>=0;--i)
          if(signed_binary[i]==0)
            complement_arr[i]=1;
          else complement_arr[i]=0;
       i=size-1;
       int carry=1;
       while(i>=0&&carry==1)
       {
           if(complement_arr[i]==0)
           {
              complement_arr[i]=1;carry=0;
           }
           else
           {
               complement_arr[i]=0;carry=1;
           }
           --i;
       }
       return complement_arr;
    }