How to convert decimal literals into hex in C, 500

2019-09-04 23:46发布

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.

2条回答
神经病院院长
2楼-- · 2019-09-04 23:56

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
查看更多
太酷不给撩
3楼-- · 2019-09-05 00:19

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.

查看更多
登录 后发表回答