Wednesday, September 10, 2014

What is 1's and 2's Compliment:

The 1's and 2's complement binary representation of numbers are used to perform addition and subtraction with negative numbers without the use of the sign bit.


1's Compliment representation is the simple inverse of each bit representing just the integer value without the sign. For example :
Represent  : -8
Binary of 8 : 00001000
1’s compliment representation of -8 : 11110111


2’s Compliment representation is 1’s Compliment + 1. For example :
Represent  : -5
Binary of 5 : 00000101
1’s compliment representation of -5 : 11111010
2’s compliment representation of -5 : (1’s compliment representation of -5 
                                                             + 1)
                                                             (11111010 + 1)
                                                             11111011

Using 2’s Compliment to perform addition with negative numbers :

Example:
2 + (-4) = -2
In Binary :
2 => 00000010
4 => 00000100
-4  => (2’s Compliment) 11111100
2                                            00000010
+
(-4)                                         11111100
                                               11111110      (-2 in 2's compliment)                                                         

Representing an integer in different formats in C++ code and using bitset:


#include <iostream>
#include <bitset>
using namespace std;
int disp_number()
{
        int i = 0;
        cout << "Enter Intiger : " ;
        cin >> i;
        cout << "decimal : " << std::dec << i << endl;
        cout << "hex : " << std::hex << i << endl;
        cout << "oct : " << std::oct << i << endl;
        cout << "Binary : " << (bitset<16>)i << endl;
        cout << "Inverse : " << bitset<16>(~i) << endl;
        i = (0 <= i)?i:(-1)*i;
        cout << "One's compliment : " << ~(bitset<16>)i << endl;
        int d = ((bitset<16>)i).flip().to_ulong();
        cout << "Two's compliment : " << bitset<16>(++d) << endl;
        return 0;
}

Enjoy... :)