Converting an int to a 2 byte hex value in C

后端 未结 15 1421
不知归路
不知归路 2020-12-05 18:17

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?

15条回答
  •  佛祖请我去吃肉
    2020-12-05 19:01

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

提交回复
热议问题