Converting an int to a 2 byte hex value in C

后端 未结 15 1437
不知归路
不知归路 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 18:57

    char s[5];  // 4 chars + '\0'
    int x = 4660;
    sprintf(s, "%04X", x);
    

    You'll probably want to check sprintf() documentation. Be careful that this code is not very safe. If x is larger than 0xFFFF, the final string will have more than 4 characters and won't fit. In order to make it safer, look at snprintf().

提交回复
热议问题