首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将二进制数组转换为其2的补码?

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

Stack Overflow用户
提问于 2015-10-09 16:01:38
回答 1查看 1.3K关注 0票数 0

我很难把它转换成2的补码。我知道问题出在哪里,但我想不出怎么解决。问题是内部for循环中的两个if语句,因为其中一个将值更改为0,另一个将其更改为1,我尝试将其更改为if和else,但随着值的增加,情况变得更加糟糕。

代码语言:javascript
复制
/*
 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;

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-10-09 16:43:31

我想您混淆了我的friend.To计算二进制数的两个补数,有两个步骤:

1.补语。

2.在补语中加1。

所以我的c代码是:

代码语言:javascript
复制
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;
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33042640

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档