Tuesday 25 September 2012

Program to find 2's complement


void revert(char *str,char *comp,int l);

int main()
{
  int i,found=0,l,stlen;
  char *str,*comp;

  clrscr();

printf("\nEnter a binary string\n");
gets(str);
stlen=strlen(str);
l=stlen;
l--;
       // printf("\nlength=%d..%c..",l,str[l]);
while(l)
{
if(found)
{
revert(str,comp,l);
break;
}
else
{
if(str[l]=='1')
found=1;
comp[l]=str[l];
printf("%c",str[l]);
l--;
}
}
printf("\ncopmlement is");
puts(comp);

getch();
return(0);
}


void revert(char *str,char *comp,int l)
{
while(l>=0)
{
if(str[l]=='1')
{printf("0");comp[l--]='0' ;}
else
{printf("1");comp[l--]='1';}
}
}

Program to Conver Hexadecimal String to Decimal number



int main()
{
char *str;
clrscr();
printf("\nEnter a hexadecimal string\n");
gets(str);

printf("\nthe corresponding decimal value is %d",htoi(str));
getch();
return(0);
}

int power (int a, int b) // utility function
{
int res = 1 ;
while( b>0 )
{
res *= a ;
b--;
}
return ( res );
}

int htoi ( char* s )
{
int result = 0,new_result;
//int value =0;
int len = strlen(s);
int exp = len;
char c;
int i;

  for( i=0; i<len; i++)
   {

    c = s[i];

     if ( c >='1' && c<='9')
new_result = (int)( (c - '0') * power(16, exp-1) );

     else
if (c >='A' && c<='F')
  new_result = (int)( (c - 55) * power(16, exp-1) );

    exp --;
    result += new_result;

   }

return (result);
}