Sergey already showed you the right way of thinking about it, that is
the hexadecimal representation of a number. He also suggested you the proper way to handle it in
C
.
Now, let me try to go a bit into the actual implementation:
#include <stdio.h>
#include <string.h>
#include <assert.h>
void step( int k, int l, char * p)
{
if ( l )
{
*p = (k & 0xF);
*p += *p < 0xA ? '0' : ('A' - 0xA);
step(k>>=4, --l, --p);
}
}
void hexstr(int n, char buf[], int bufsize)
{
int len = 2 * sizeof(n);
assert(buf && bufsize > len);
buf[len] = '\0';
step(n, len, &buf[len-1]);
}
int main()
{
int n;
char buf[2*sizeof(n)+1];
printf("please enter a number\n");
if ( scanf("%d", &n) == 1)
{
hexstr(n, buf, sizeof(buf));
printf("the hexadecimal representation of %d is %s\n", n, buf);
}
return 0;
}
[update]
This one recursively
prints the hexadecimal representation of the number without using arrays.
#include <stdio.h>
#include <string.h>
#include <assert.h>
void hexstep( unsigned int k, int l)
{
if ( l )
{
hexstep (k >> 4, --l);
}
char c = (char) (k & 0xF);
printf("%c", c < 0xA ? c + '0' : c + 'A' - 0xA);
}
int main()
{
unsigned int n;
printf("please enter a number\n");
if ( scanf("%u", &n) == 1)
{
printf("the hexadecimal representation of %u is ", n);
hexstep(n, sizeof(n)*2-1);
printf("\n");
}
return 0;
}
[/update]