Below is a C program which takes as input a decimal number and prints the two's complement of that number. The given decimal number is first converted to binary format. Then we find the 1's complement and then add one to the one's complement to get the required 2's complement of the given decimal number.
/*Program to find the two's complement of given number*/
main()
{
int num,tnum,tbin[16],bin[16],one[16],fin[16],i,j,k,quot,rem,sum=0,carry=0;
clrscr();
/*Reading the decimal number from user*/
printf("Enter a decimal number:");
scanf("%d", &num);
/*Converting decimal number to binary*/
tnum = num;
i = 0;
while(num > 0)
{
tbin[i] = num % 2;
num = num / 2;
i++;
}
for(k=0,j=i-1;j>=0;j--,k++)
bin[k] = tbin[j];
/*Printing the binary number*/
printf("Binary representation of %d is: ",tnum);
for(k=0;k<i;k++)
printf("%d",bin[k]);
/*One's complement of the number*/
for(k=0;k<i;k++)
{
if(bin[k]==0)
bin[k] = 1;
else
bin[k] = 0;
}
/*Printing one's complement*/
printf("\nOne's complement of %d is: ",tnum);
for(k=0;k<i;k++)
printf("%d",bin[k]);
/*Creating binary number 1 for adding to the one's complement*/
for(k=0;k<i-1;k++)
{
one[k] = 0;
}
one[i-1] = 1;
/*Two's complement of the number*/
for(k=i-1;k>=0;k--)
{
/*printf("\nbin[%d] = %d, one[%d] = %d",k,bin[k],k,one[k]);*/
if(bin[k]==1 && one[k]==1)
{
sum = 0;
carry = 1;
}
else if(bin[k]==0 && one[k]==0)
{
if(carry==1)
{
sum = 1;
carry = 0;
}
else
{
sum = 0;
carry = 0;
}
}
else
{
if(carry==1)
{
sum = 0;
carry = 1;
}
else
{
sum = 1;
carry = 0;
}
}
fin[k] = sum;
/*printf("\nsum = %d, carry = %d",sum,carry);*/
}
/*Printing 2's complement*/
printf("\n2's complement of %d is: ",tnum);
for(k=0;k<i;k++)
printf("%d",fin[k]);
getch();
}
Sample input and output:
Enter a decimal number:36
Binary representation of 36 is: 100100
One's complement of 36 is: 011011
2's complement of 36 is: 011100
No comments:
Post a Comment