ตัวเลขไบนารีแสดงในฐาน 2 ใช้เลข 0 และ 1 เท่านั้น แต่ละหลักเรียกว่า bit
ตัวอย่างตัวเลขไบนารี = 0100010111
1's Complement
1's complement ได้จากการกลับบิตของตัวเลขไบนารี คือเปลี่ยน 1 เป็น 0 และ 0 เป็น 1
ตัวอย่าง
1's Complement of 101100 = 010011
2's Complement
2's complement ได้จากการบวก 1 เข้าไปใน 1's complement คือ 1's complement + 1
ตัวอย่าง
2's complement of 101101 is 010011.
โค้ดตัวอย่าง
โค้ดหา 1's และ 2's complement
#include <iostream> #include<string.h> using namespace std; int main() { char binary[10] = "01001011"; cout<<"Binary number is "<<binary; int length = strlen(binary); for(int i=0;i<length;i++) { if(binary[i] == '0') { binary[i]= '1'; } else binary[i] = '0'; } cout<<"One's Complement is "<<binary<<endl; for(int i = length-1; i>=0; i--) { if(binary[i] == '0') { binary[i] = '1'; break; } else { binary[i] = '0'; } } cout<<"Two's complement is "<<binary; return 0; }ผลลัพธ์
Binary number is 01001011 One's complement is 10110100 Two's complement is 10110101