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?
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];