Home > Backend Development > C++ > body text

What are the 1's complement and 2's complement of binary numbers?

WBOY
Release: 2023-09-11 23:33:02
forward
1652 people have browsed it

What are the 1s complement and 2s complement of binary numbers?

Binary numbers are represented in base 2. It only uses the two digits "0" and "1". Each digit in a binary number is a bit.

Example binary number - 0100010111

1's complement number

The binary number's complement number is by reversing the digits of the binary number, that is, 1 is converted to 0, and 0 is converted is obtained as 1.

Example

1’s Complement of 101100 = 010011
Copy after login

2's complement

The complement of a binary number is the complement of the binary number plus 1, that is, 1's complement of 1.

Example

2’s complement of 101101 is 010011.
Copy after login

Sample code

Code to find one and two's complement -

#include <iostream>
#include<string.h>
using namespace std;
int main() {
   char binary[10] = "01001011";
   cout<<&ldquo;Binary number is &rdquo;<<binary;
   //once complement....
   int length = strlen(binary);
   for(int i=0;i<length;i++) {
      if(binary[i] == &#39;0&#39;) {
         binary[i]= &#39;1&#39;;
      } else
         binary[i] = &#39;0&#39;;
   }
   cout<<&ldquo;One&rsquo;s Complement is &rdquo;<<binary<<endl;
   // cout<<binary[length-1];
   for(int i = length-1; i>=0; i--) {
      // cout<<binary[i];
      if(binary[i] == &#39;0&#39;) {
         binary[i] = &#39;1&#39;;
         //cout<<binary[i];
         break;
      } else {
         binary[i] = &#39;0&#39;;
      }
   }
   cout<<&ldquo;Two&rsquo;s complement is &rdquo;<<binary;
   return 0;
}
Copy after login

Output

Binary number is 01001011
One&rsquo;s complement is 10110100
Two&rsquo;s complement is 10110101
Copy after login

The above is the detailed content of What are the 1's complement and 2's complement of binary numbers?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!