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?
Most of these answers are great, there's just one thing I'd add: you can use sizeof to safely reserve the correct number of bytes. Each byte can take up to two hex digits (255 -> ff), so it's two characters per byte. In this example I add two characters for the '0x' prefix and one character for the trailing NUL.
int bar;
// ...
char foo[sizeof(bar) * 2 + 3];
sprintf(foo, "0x%x", bar);
void intToHex(int intnumber, char *txt)
{
unsigned char _s4='0';
char i=4;
//intnumber=0xffff;
do {
i--;
_s4 = (unsigned char) ((intnumber >> i*4 ) & 0x000f);
if(_s4<10)
_s4=_s4+48;
else
_s4=_s4+55;
*txt++= _s4;
} while(i);
}
...
char text [5]={0,0,0,0,0};
...
intToHex(65534,text);
USART_Write_Text(text);
....
Perhaps try something like this:
void IntToHex(int value, char* buffer) {
int a = value&16;
int b = (value>>4)&16;
buffer[0] = (a<10)?'0'+a:'A'-(a-10);
buffer[1] = (b<10)?'0'+b:'A'-(b-10);
}
For dynamic fixed length of hex
string makeFixedLengthHex(const int i, const int length)
{
std::ostringstream ostr;
std::stringstream stream;
stream << std::hex << i;
ostr << std::setfill('0') << std::setw(length) << stream.str();
return ostr.str();
}
But negative you have to handle it yourself.
If you're allowed to use library functions:
int x = SOME_INTEGER;
char res[5]; /* two bytes of hex = 4 characters, plus NULL terminator */
if (x <= 0xFFFF)
{
sprintf(&res[0], "%04x", x);
}
Your integer may contain more than four hex digits worth of data, hence the check first.
If you're not allowed to use library functions, divide it down into nybbles manually:
#define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)
int x = SOME_INTEGER;
char res[5];
if (x <= 0xFFFF)
{
res[0] = TO_HEX(((x & 0xF000) >> 12));
res[1] = TO_HEX(((x & 0x0F00) >> 8));
res[2] = TO_HEX(((x & 0x00F0) >> 4));
res[3] = TO_HEX((x & 0x000F));
res[4] = '\0';
}
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()
.