首页 > 后端开发 > C++ > 正文

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

PHPz
发布: 2023-09-18 09:17:05
转载
1488人浏览过

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

给定二进制数的补码可以通过两种方法计算,如下 -

  • 方法 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</p><p>",num, two);
登录后复制

从给定的二进制数中找到补码的逻辑是 −

码上飞
码上飞

码上飞(CodeFlying) 是一款AI自动化开发平台,通过自然语言描述即可自动生成完整应用程序。

码上飞 138
查看详情 码上飞
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</p><p>",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</p><p>");
   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</p><p>",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</p><p>",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
登录后复制

以上就是给定一个数,找到它的二进制补码的C程序的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号