I need to convert an int to a 2 byte hex value to store in a char array, in C. How can I do this?
Here's a crude way of doing it. If we can't trust the encoding of ascii values to be consecutive, we just create a mapping of hex values in char. Probably can be optimized, tidied up, and made prettier. Also assumes we only look at capture the last 32bits == 4 hex chars.
#include
#include
#define BUFLEN 5
int main(int argc, char* argv[])
{
int n, i, cn;
char c, buf[5];
char hexmap[17] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','.'};
for(i=0;i\n", argv[0]);
return 1;
}
n = atoi(argv[1]);
i = 0;
printf("n: %d\n", n);
for(i=0; i<4; i++)
{
cn = (n>>4*i) & 0xF;
c = (cn>15) ? hexmap[16] : hexmap[cn];
printf("cn: %d, c: %c\n", cn, c);
buf[3-i] = (cn>15) ? hexmap[16] : hexmap[cn];
}
buf[4] = '\0'; // null terminate it
printf("buf: %s\n", buf);
return 0;
}