
给定二进制数的补码可以通过两种方法计算,如下 -
对于给定的二进制数查找二进制补码的逻辑如下 -
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
} else {
two[i] = one[i];
}
}
two[SIZE] = ' ';
printf("Two's complement of binary number %s is %s",num, two);
从给定的二进制数中找到补码的逻辑是 −
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = ' ';
printf("Ones' complement of binary number %s is %s",num, one);
示例
以下是查找给定数字的补码的 C 程序 -
现场演示
#include<stdio.h>
#include<stdlib.h>
#define SIZE 8
int main(){
int i, carry = 1;
char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
printf("Enter the binary number");
gets(num);
for(i = 0; i < SIZE; i++){
if(num[i] == '0'){
one[i] = '1';
}
else if(num[i] == '1'){
one[i] = '0';
}
}
one[SIZE] = ' ';
printf("Ones' complement of binary number %s is %s
",num, one);
for(i = SIZE - 1; i >= 0; i--){
if(one[i] == '1' && carry == 1){
two[i] = '0';
}
else if(one[i] == '0' && carry == 1){
two[i] = '1';
carry = 0;
}
else{
two[i] = one[i];
}
}
two[SIZE] = ' ';
printf("Two's complement of binary number %s is %s
",num, two);
return 0;
}
输出
当
.........................................................