How to convert decimal literals into hex in C, 500 to 0x0500

十年热恋 提交于 2019-12-25 06:46:08

问题


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.



来源:https://stackoverflow.com/questions/7448054/how-to-convert-decimal-literals-into-hex-in-c-500-to-0x0500

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!