0
votes

Following simple decimal to binary, oct or hex conversion fails. Following is a problem statement,

Write a function called itoc(), which converts an unsigned integer to a binary, octal, or hexadecimal character string. Pass the conversion base as a parameter to itoc() and have it return a NULL terminated character string.

The first part where I convert an input number in reverse order. These intermediate results correct (or may be I perceive it correct). The final reversal returns nothing. The watch window on 2 character array str[] and outPutString[] shows following... which think an error in my code but I am unable to figure out what is missing.

enter image description here

//itoc.c
    
#include <stdio.h>
#include <string.h>

char *itoc(unsigned int, unsigned int);

int main(void)
{
   // variable to store base and decimal number for conversion
   unsigned int base, number;

   printf("Enter <number> and <base> here: ");
   scanf("%u %u", &number, &base);
   printf("%u is %s\n", number, itoc(base, number));

   return 0;
}

// function converts any decimal number and convert based upon base
char *itoc(unsigned int base, unsigned int number)
{
   static char str[80], outPutStr[80];       //string to hold the intermediate
                                             // results and final result
   char *ptrChar, *ptrEnd;                   // current location and final location
   unsigned int digit;

   //divide a number by base and append the remainder to an intermediate array continue to divide the 
   //number until remainder is zero. in case of hex, number greater than 9 are added with offset
   for(ptrChar = str; number > 0;)
   {
      digit = number % base;
      
      if(digit <= 9)
         *ptrChar++ = digit + '0';
      else
         *ptrChar++ = digit + 'A' - 10;

      number /= base;
   }
   *ptrChar = '\0';                       // terminate the array

   ptrChar = outPutStr;
   ptrEnd = str + (int)strlen(str);       // point to the last location of
                                          // intermediate array

   // un-reverse the internediate array holds converted number in reverse order
   for(; ptrEnd >= str;)
   {
      *ptrChar++ = *ptrEnd--;
   }
   *ptrChar = '\0';

   return outPutStr;                      // return pointer to final result
}
1
Tip: for ( ; cond ;) is a clumsy way of saying while (cond).tadman
Probably on off-by-one error as you start by copying the '\0' terminating character first.dratenik

1 Answers

1
votes

Here's the problem:

ptrEnd = str + (int)strlen(str);       

The end pointer starts off pointing to the null terminating byte at the end of the string. So you swap that with the first character, and now your string starts with a null byte, giving you an empty string.

Change it to point to the last character in the string:

ptrEnd = str + (int)strlen(str) - 1;