Skip to content

Instantly share code, notes, and snippets.

@khakimov
Created August 12, 2012 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khakimov/3329057 to your computer and use it in GitHub Desktop.
Save khakimov/3329057 to your computer and use it in GitHub Desktop.
decimal to hexadecimal
/*
Exercise 3-4 K&R.
To convert a decimal number x to hexadecimal, we can repeatedly divide x by 16,
giving a quotient q and a remainder r, such that x = q * 16 + r.
*/
#include <stdio.h>
void itoh(int n);
int convert(int s);
int main()
{
itoh(314156);
return 0;
}
void itoh(int n)
{
int i = 0, j =0;
char buf[100];
while(n != 0)
{
i = n % 16;
if (i > 0)
{
buf[j++] = convert(i);
n = (n - i) / 16;
}
}
buf[j] = '\0';
printf("%s\n", buf);
}
int convert(int s)
{
int c;
char hex[] = {'A', 'B', 'C', 'D', 'E', 'F'};
c = (s > 0 && s < 9) ? s + '0' : hex[s - 10];
return c;
}
@solalsabbah
Copy link

What if i = 16 or i = 32 ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment