COME ON CODE ON

A blog about programming and more programming.

Number System Conversion

with 3 comments

I gave this question in one of the contests to interconvert between decimal,octal and hexdecimal numbers without traversing the digits. The numbers could be random like 12 0xA 15 o12. You have to print the number in other two systems except from the one entered. The program would be terminated by a negative number. The solution i gave uses sscanf and was as following :

int main()
{
    char str[20];
    int dec,l,i,n;
    while (1)
    {
          scanf("%s",str);
          if (str[0]=='-')
             break;
          else if (str[1]=='x')
          {
               str[0]=str[1]=' ';
               sscanf(str,"%X",&n);
               printf("%d o%o\n",n,n);
          }
          else if (str[0]=='o')
          {
               str[0]=' ';
               sscanf(str,"%o",&n);
               printf("%d 0x%X\n",n,n);
          }
          else
          {
              n=atoi(str);
              printf("0x%X o%o\n",n,n);
          }
    }
}

If you have a better solution please post it in the comments.

-fR0D

Advertisements

Written by fR0DDY

February 23, 2009 at 12:55 PM

Posted in Maths, Programming

Tagged with ,

3 Responses

Subscribe to comments with RSS.

  1. hehe.. nice trick. 😀

    jrharshath

    February 23, 2009 at 2:32 PM

  2. sscanf , sprintf
    ye mujhe book me nahi mile .
    badhiya hai !

    manoj

    February 24, 2009 at 12:00 PM

  3. instead of using
    printf(“%d o%o\n”,n,n);
    u can directly use printf(“%d %#o\n”,n,n);

    similarly
    printf(“%d 0x%X\n”,n,n);
    can be replaced by printf(“%d %#X\n”,n,n);

    and
    printf(“0x%X o%o\n”,n,n); by printf(“%#X %#o\n”,n,n);

    Gaurav Gupta

    March 5, 2009 at 2:02 PM


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: