您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

给定一个数,找到它的二进制补码的C程序

2024/3/12 22:17:13发布18次查看
给定二进制数的补码可以通过两种方法计算,如下 -
方法 1 − 将给定的二进制数转换为补码,然后加 1。
方法 2 − 从 least 开始设置的第一个位后面的尾随零有效位 (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
",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
",num, one);
示例以下是查找给定数字的补码的 c 程序 -
 现场演示
#include<stdio.h>#include<stdlib.h>#define size 8int 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] = '\0'; 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] = '\0'; printf("two's complement of binary number %s is %s
",num, two); return 0;}
输出当执行上述程序时,会产生以下结果 -
enter the binary number1000010ones' complement of binary number 1000010 is 0111101two's complement of binary number 1000010 is 0111110
以上就是给定一个数,找到它的二进制补码的c程序的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product