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 <stdlib.h>
#include <stdio.h>
#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<BUFLEN;i++)
buf[i]=0;
if(argc<2)
{
printf("usage: %s <int>\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;
}
Assuming int to be 32 bits;
easiest way: just use sprintf()
int intval = /*your value*/
char hexval[5];
sprintf(hexval,"%0x",intval);
Now use hexval[0] thru hexval[3]; if you want to use it as a null-terminated string then add hexval[4]=0;
Using Vicky's answer above
typedef unsigned long ulong;
typedef unsigned char uchar;
#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)
#define max_strhex (sizeof(ulong)*2)
public uchar
*mStrhex(uchar *p, ulong w, ulong n)
{
ulong i = 0xF; // index
ulong mask = i << (((sizeof(ulong)*2)-1)*4); // max mask (32 bit ulong mask = 0xF0000000, 16 bit ulong mask = 0xF000)
ulong shift = (w*4); // set up shift to isolate the highest nibble
if(!w || w > max_strhex) // no bold params
return p; // do nothing for the rebel
mask = mask >> (max_strhex-w)*4; // setup mask to extract hex nibbles
for(i = 0; i < w; i++){ // loop and add w nibbles
shift = shift - 4; // hint: start mask for four bit hex is 0xF000, shift is 32, mask >> 32 is 0x0000, mask >> 28 is 0x000F.
*p++ = TO_HEX(((n & mask) >> shift)); // isolate digit and make hex
mask = mask >> 4; //
*p = '\0'; // be nice to silly people
} //
return p; // point to null, allow concatenation
}