Thread: I need some help with a base converter

  1. #1
    Unregistered
    Guest

    I need some help with a base converter

    This function is supposed to convert decimal to hex, but when I run it instead of letters/appropriate ints in front it outputs 3 as the first int,
    eg 17(converted is supposed to be 11)->comes out 31
    Could someone pleaaase look at my code and see whats wrong?
    (I need it in first principles so I can't use the easy X way)
    #include <stdio.h>

    void decimal2hex(int num, char hexstring[])
    {
    int remain=0,x,last=0;
    hexstring[last]='\0';

    do
    {
    remain=num%16;
    num=num/16;

    for(x=last++;x>=0;x--)
    hexstring[x+1]=hexstring[x];
    hexstring[0]=remain>9?'A'+(remain-10):'0'+remain;
    }while(num!=0);
    }

    int main(int argc, char *argv[])
    {
    int num;
    char hexstring[100];

    num=getchar();
    decimal2hex(num,hexstring);
    printf("%s\n",hexstring);
    return 0;
    }

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    last=0;
    hexstring[last]='\0';

    do
    {
    remain=num%16;
    num=num/16;

    for(x=last++;x>=0;x--)
    Notice anything?

    last = 0;

    do
    {
    for( x = last++; x >= 0; x-- )



    Notice anything? x is zero. Your loop will only execute once.

    Quzah.
    Hope is the first step on the road to disappointment.

  3. #3
    Unregistered
    Guest
    oooh....oops.
    Thanks lots!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Base Converter Part 2
    By encyclopedia23 in forum C Programming
    Replies: 2
    Last Post: 12-30-2006, 02:42 PM
  3. Base Converter
    By encyclopedia23 in forum C Programming
    Replies: 3
    Last Post: 12-29-2006, 08:55 AM
  4. Base10 to Base n converter
    By P4r4digm in forum C++ Programming
    Replies: 1
    Last Post: 10-04-2006, 09:34 PM
  5. Base converter libary
    By cdonlan in forum C++ Programming
    Replies: 22
    Last Post: 05-15-2005, 01:11 AM