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?
Figured out a quick way that I tested out and it works.
int value = 11;
array[0] = value >> 8;
array[1] = value & 0xff;
printf("%x%x", array[0], array[1]);
result is:
000B
which is 11 in hex.
unsigned int hex16 = ((unsigned int) input_int) & 0xFFFF;
input_int
is the number you want to convert. hex16
will have the least significant 2 bytes of input_int
. If you want to print it to the console, use %x
as the format specifier instead of %d
and it will be printed in hex format.
Normally I would recommend using the sprintf
based solutions recommended by others. But when I wrote a tool that had to convert billions of items to hex, sprintf was too slow. For that application I used a 256 element array, which maps bytes to strings.
This is an incomplete solution for converting 1 byte, don't forget to add bounds checking, and make sure the array is static or global, recreating it for every check would kill performance.
static const char hexvals[][3]= {"00", "01", "02", ... "FD", "FE", "FF"};
const char *byteStr = hexvals[number];
you can use this it is simple and easy to convert
typedef union {
struct hex{
unsigned char a;
unsigned char b;
}hex_da;
short int dec_val;
}hex2dec;
hex2dec value;
value.dec_val=10;
Now hex value is stored in hex_da structure access it for further use.
This function works like a charm.
void WORD2WBYTE(BYTE WBYTE[2], WORD Value) {
BYTE tmpByte[2];
// Converts a value from word to word byte ----
memcpy(tmpByte, (BYTE*) & Value, 2);
WBYTE[1] = tmpByte[0];
WBYTE[0] = tmpByte[1];
}
asumming the following:
typedef unsigned char BYTE;
typedef unsigned short WORD;
Example of use:
we want to achieve this:
integer = 92
byte array in hex:
a[0] = 0x00;
a[1] = 0x5c;
unsigned char _byteHex[2];
WORD2WBYTE(_byteHex, 92);
Rather than sprintf
, I would recommend using snprintf
instead.
#include <stdio.h>
int main()
{
char output[5];
snprintf(output,5,"%04x",255);
printf("%s\n",output);
return 0;
}
Its a lot safer, and is available in pretty much every compiler.