주어진 이진수에 대한 2의 보수는 다음과 같은 두 가지 방법으로 계산할 수 있습니다. -
-
방법 1 − 주어진 이진수를 1의 보수로 변환하고 1을 더합니다.
-
방법 2 − LSB(Least Significant Bit)에서 설정한 첫 번째 비트 이후의 후행 0은 변경되지 않고 남아 있는 모두를 포함하여 보완되어야 합니다.
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\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); 예시
다음은 주어진 숫자에 대한 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\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