gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:22:00 25 4
gpt4 key购买 nike

我在尝试转换为 2 的补码时遇到了问题。我知道问题出在哪里,但我不知道如何解决。问题是内部 for 循环中的两个 if 语句,因为一个将值更改为 0,然后另一个将其更改回 1。我尝试将其更改为 if 和 else 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;

}

最佳答案

我想你是糊涂了我的 friend 。要计算二进制数的补码,有两个步骤:

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

关于c - 如何将二进制数组转换为其 2 的补码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33042640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com