Wednesday, 23 May 2012

2's Complement using C Programming

Definition

Property
Two's complement representation allows the use of binary arithmetic operations on signed integers, yielding the correct 2's complement results.

Positive Numbers
Positive 2's complement numbers are represented as the simple binary.

Negative Numbers
Negative 2's complement numbers are represented as the binary number that when added to a positive number of the same magnitude equals zero.
Integer2's Complement
SignedUnsigned
550000 0101
440000 0100
330000 0011
220000 0010
110000 0001
000000 0000
-12551111 1111
-22541111 1110
-32531111 1101
-42521111 1100
-52511111 1011
Note:  The most significant (leftmost) bit indicates the sign of the integer; therefore it is sometimes called the sign bit.
If the sign bit is zero,
then the number is greater than or equal to zero, or positive.
If the sign bit is one,
then the number is less than zero, or negative.

Calculation of 2's Complement

To calculate the 2's complement of an integer, invert the binary equivalent of the number by changing all of the ones to zeroes and all of the zeroes to ones (also called 1's complement), and then add one.
For example,
0001 0001(binary 17)   such that   1110 1111(two's complement -17)
NOT(0001 0001) = 1110 1110  (Invert bits)
1110 1110 + 0000 0001 = 1110 1111  (Add 1)


2's Complement Addition

Two's complement addition follows the same rules as binary addition.
For example,
5 + (-3)  =  2     0000 0101 = +5
+ 1111 1101

 = -3
  0000 0010 = +2
Finally a C program to perform addition using 2's Complement.

#include<stdio.h>
#include<conio.h>
#include<math.h>
void showbits(int,int);

void main()
{
 int a,b,c,bit,d,e,f,g,i;
 char ch;
 do
 {
  clrscr();

  //accepting inputs
  printf("\nEnter the number of bits: ");
  scanf("%d",&bit);
  printf("Enter two numbers to be added:- \n");
  scanf("%d",&a);
  scanf("%d",&b);
  c=a+b;

  //Ones Complement
  d=~(a);
  e=~(b);

  if(a<0)
   f=a;
  else
   f=d+1;

  if(b<0)
   g=b;
  else
   g=e+1;

  //addition
  printf("\nAddition: \n");
  printf("\t ");
  showbits(f,bit);
  printf("\n");
  printf("\t+");
  showbits(g,bit);
  printf("\n\t");

  for(i=0;i<=bit;i++)
   printf("-");

  printf("\t ");
  showbits(c,bit);
  printf("\n");
  printf("\t= %d",c);

  if(c>=(-1*(pow(2,bit-1)))&&(c<=(pow(2,bit-1)-1)))
   printf("\n\nResult Status: No Overflow \n");
  else
   printf("\n\nResult Status: Overflow \n");

  printf("\n\n\nDo you wish to continue? (y/n)");

  ch=getch();
 }while(ch=='y');
}

void showbits(int n,int bit)
{
 int i,k,andmask;

 for(i=(bit-1);i>=0;i--)
 {
  andmask=1<<i;
  k=n & andmask;

  k==0?printf("0"):printf("1");
 }
}

No comments:

Post a Comment

Your comments are very much valuable for us. Thanks for giving your precious time.