Search code examples
carraystwos-complement

How do I convert a binary array to its 2's complement?


I'm having trouble with trying to convert to 2's complement. I know what the problem is but I can't figure out how to fix it. The problem is the two if statements in the inner for loop because one changes the value to 0 and then the other one changes it back to 1. I tried changing it to if and else if but it got even worse with the values.

/*
 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;

}

Solution

  • I think You are confused my friend.To calculate two's complement of a binary number,there are two steps:

    1.Take the one's complement.

    2.Add 1 to the one's complement.

    So my c code would be:

    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;
        }