Two's Complement** คือวิธีแสดงตัวเลขลบในคอมพิวเตอร์ ใช้กันอย่างแพร่หลายในระบบ Binary
วิธีคำนวณ (2 วิธี)
วิธีที่ 1: One's Complement + 1
- หา One's Complement (กลับบิต: 0→1, 1→0)
- บวก 1 เข้าไป
วิธีที่ 2: จาก LSB (Least Significant Bit)
- คัดลอกบิตจากขวาสุดจนถึง '1' ตัวแรก (รวม '1' ตัวนั้น)
- กลับบิตที่เหลือทางซ้าย
ตัวอย่าง: 1000010 (Binary)
วิธี 1:
Original: 1 0 0 0 0 1 0 One's Comp: 0 1 1 1 1 0 1 Add 1: 0 1 1 1 1 1 0 ← Two's Complement
วิธี 2:
Original: 1 0 0 0 0 1 0
↑ ↑
Copy First '1' from right
Keep: 1 0
Flip left: 0 1 1 1 1
Result: 0 1 1 1 1 1 0
โค้ด C: หา One's และ Two's Complement
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 8
int main() {
char num[SIZE + 1], one[SIZE + 1], two[SIZE + 1];
int i, carry = 1;
printf("Enter %d-bit binary number: ", SIZE);
scanf("%s", num);
// Validate input
for(i = 0; i < SIZE; i++) {
if(num[i] != '0' && num[i] != '1') {
printf("Invalid binary number!\n");
return 1;
}
}
// One's Complement
for(i = 0; i < SIZE; i++) {
one[i] = (num[i] == '0') ? '1' : '0';
}
one[SIZE] = '\0';
// Two's Complement (One's + 1)
for(i = SIZE - 1; i >= 0; i--) {
if(one[i] == '1' && carry == 1) {
two[i] = '0';
carry = 1;
} else if(one[i] == '0' && carry == 1) {
two[i] = '1';
carry = 0;
} else {
two[i] = one[i];
}
}
two[SIZE] = '\0';
printf("Original: %s\n", num);
printf("One's Comp: %s\n", one);
printf("Two's Comp: %s\n", two);
return 0;
}
ผลลัพธ์
Enter 8-bit binary number: 1000010 Original: 1000010 One's Comp: 0111101 Two's Comp: 0111110
ความหมายของ Two's Complement
| Binary (8-bit) | Unsigned | Signed (Two's Comp) |
|---|---|---|
| 00000000 | 0 | 0 |
| 01111111 | 127 | 127 |
| 10000000 | 128 | -128 |
| 11111111 | 255 | -1 |
| 10000001 | 129 | -127 |
การใช้งานจริง
- CPU ใช้ Two's Complement สำหรับ Signed Integer
- การลบ: A - B = A + (Two's Complement of B)
- Overflow Detection: Carry In ≠ Carry Out ของ MSB
ฟังก์ชันสำเร็จรูป (GCC/Clang)
// Built-in functions
int x = 10;
int neg = -x; // Two's complement
unsigned ux = (unsigned)-x; // As unsigned
// หรือ
int twos = ~x + 1; // Manual: One's complement + 1