查找给定数字的 2 的补码的 C 语言程序
可通过两种方法来计算给定二进制数的 2 的补码,如下所示 −
方法 1 − 将给定的二进制数转换为 1 的补码,然后加 1。
方法 2 − 找到从最低有效位 (LSB) 开始并包括位保持不变的第一个设置位之后的尾随零,并对所有其他位取补。
查找给定二进制数的 2 的补码的逻辑如下 −
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);查找给定二进制数的 1 的补码的逻辑为 −
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);范例
以下是用来查找给定数字的 2 的补码的 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] = '\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 number 1000010 Ones' complement of binary number 1000010 is 0111101 Two's complement of binary number 1000010 is 0111110
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP