Finding 1s and 2s complement of a number – C Tutorial

In this c programming tutorial we are going to see how we find 1s and 2s complement of number. To find 1st complement of a given binary number we just need to invert each binary digit from given binary number. For example,
Let, given binary number is  1111 0000.
Then its 1st complement is  0000 1111.
Here we just inverted each bit value, means where there is ‘1’ then it should change to ‘0’ and vice versa.
To represent this logic in c program code we will just need to take binary number as input from user and then need to check value of each bit and change it (if ‘1’ then change it to ‘0’ and vice versa) until the end of number. This can simply done by declaring a character array and one function say ‘first()’ in a program to find first complement of a number.
Now to find 2nd complement of number procedure is to find first complement first and the add binary ‘1’ to the first complement. For example,
Let, given binary number is  1110 0010.
Then its first complement is 0001 1101.
And 2’s complement is          0001 1101                      ß 1st complement
                                                +                     1                       ß Add  ‘1’
                                                    0001 1110          
Now to do this programmatically, we need to read number from user in a character array (as shown in program) and then need to find first complement of the number, after that point the last location in character array using pointer (*c from the code from ‘second ()’ function) because while doing addition or subtraction we proceed from the last digit (unit place). Next we simply need to check the values within that pointer, if that value is ‘1’ then change it ‘0’ and decrement the pointer else if that value is ‘0’ simply change it to ‘1’ and don’t decrement the pointer this time.


Leave a comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: