ส่วนเติมเต็มของทั้งสองสำหรับเลขฐานสองที่กำหนดสามารถคำนวณได้สองวิธี ได้แก่ −
-
วิธีที่ 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<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