How to convert decimal literals into hex in C, 500

2019-09-05 00:11发布

问题:

I have the following: int num=500; char text[8];

how do I make it so that text ends up being the hex 0x500, or 1280?

edit: i see that its pretty simple to make it text, like in some of the answers. But I need this text to be interpreted as a hex by C. So in reality it should be an unsigned hex int.

回答1:

This should do it.

int num = 500;
char text[8];
sprintf(text, "0x%d", num); // puts "0x500" in text

This is assuming you on purposely didn't convert num to hexadecimal, if this wasn't on purpose this creates text with the integer converted to hexadecimal:

int num = 500;
char text[8];
sprintf(text, "0x%X", num); // puts "0x1F4" in text


回答2:

There is an exercise in K&R, second chapter if I'm not mistaken, that asks to do this very thing. If you are having difficulties I suggest you look up hexadecimal aritmetic on Wikipedia.