I have already completed my hex to integer conversion function which works properly with the provided driver. However, my integer to hex function gets stuck in an infinite loop and I have no clue why. The red section of my code is the function which is giving me problems. Everything else works; however, is a rough draft so please don't give me crap about my other functions or drivers. They are all under construction. The Second code is my instructors driver he provided my class with. The line in green is a line I changed to allocate the correct memory size.
Thank You!
blade71(106)% cat xbits.c
/*
* stubs for functions to study
* integer-hex conversions
*
*/
#include "xbits.h" /* Just prototypes...same as file */
/* Helpful function to get around not being able to use strchr()
* Converts hex to decimal value
*/
int hex_To_dec(int c)
{
char hex_values[] = "aAbBcCdDeEfF";
int i;
int answer = 0;
for (i=0; answer == 0 && hex_values[i] != '\0'; i++)
{
if (hex_values[i] == c)
{
answer = 10 + (i/2);
}
}
return answer;
}
/* function represents the int n as a hexstring which it places in the
hexstring array */
void itox( char hexstring[], int n)
{
printf("in itox, processing %d\n",n);
int number;
n = number;
int i;
hexstring[0] = '0';
hexstring[1] = 'x';
while (number != '0')
{
i = 2;
hexstring[i] = (number%16) < 10 ? (number%16) : 'A' + (number%16) - 10;
i++;
}
}
/* function converts hexstring array to equivalent integer value */
int xtoi(char hexstring[])
{
printf("in xtoi, processing %s\n", hexstring);
int answer = 0;
int i = 0;
int valid = 1;
int hexit;
if (hexstring[i] == '0')
{
++i;
if (hexstring[i] == 'x' || hexstring[i] == 'X')
{
++i;
}
}
while(valid && hexstring[i] != '\0')
{
answer = answer * 16;
if(hexstring[i] >='0' && hexstring[i] <= '9')
{
answer = answer + (hexstring[i] - '0');
}
else
{
hexit = hex_To_dec(hexstring[i]);
if (hexit == 0)
{
valid = 0;
}
else
{
answer = answer + hexit;
}
}
++i;
}
if(!valid)
{
answer = 0;
}
return answer;
}
Driver Code (Instructor Provided):
#include <stdio.h>
#include "xbits.h"
#define ENOUGH_SPACE 1 /* not really enough space */
int main()
{
char hexstring[2*sizeof(int) +1];
int m=0, n = 0xABC45;
itox( hexstring, n);
/* for stub testing: create a fake input string */
strcpy( hexstring, "ABC45");
m= xtoi(hexstring);
printf("\t%12d %s %12d\n", n,hexstring, m);
return 0; /* everything is just fine */
}