C 程序以查找给定数字的二进制补码!
可以用两种方法计算给定二进制数的二进制补码,如下所示-
方法1-将给定的二进制数转换为补码,然后加1。
方法2-从最低有效位(LSB)设置的第一位之后的尾随零,包括保持不变和其余全部应补码。
为给定的二进制数找到二进制补码的逻辑如下-
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] = '\0';
printf("Two's complement of binary number %s is %s\n",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] = '\0';
printf("Ones' complement of binary number %s is %s\n",num, one);示例
以下是用于查找给定数字的二进制补码的C程序-
#include输出结果#include #define SIZE 8 int main(){ int i, carry = 1; char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1]; printf("Enter the binary number\n"); 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] = '\0'; printf("Ones' complement of binary number %s is %s\n",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] = '\0'; printf("Two's complement of binary number %s is %s\n",num, two); return 0; }
执行上述程序时,会产生以下结果-
Enter the binary number 1000010 Ones' complement of binary number 1000010 is 0111101 Two's complement of binary number 1000010 is 0111110
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短