How do I convert a decimal integer into a single hexadecimal character? (C)
I am tr开发者_开发问答ying to convert a decimal integer into hexadecimal. I've done a lot of searching online, and have found many ways to do this. However, every way I found converts to a string; for example, I can convert 100 into "64". That isn't what I need to do. I want to be able to convert 100 into '0x64', which is an entirely different matter. For some reason, I suspect the answer to be extremely simple, but I can't seem to find/remember it. I'm writing in the C Programming Language, just to clarify. Any assistance or ideas would be much appreciated.
Thanks, Hassan
You can't "convert" a number from decimal to hexadecimal because it's ... a number (usually stored in memory as two's complement). All representations of the same number in all possible positional systems live at exactly the same point on the number line. You can though print it in different bases:
int num = 15;
printf( "%d", num ); /* prints 15 */
printf( "0x%x", num ); /* prints 0xf */
printf( "0%o", num ); /* prints 017 (octal) */
num = 0xf;
printf( "%d", num ); /* prints 15 */
printf( "0x%x", num ); /* prints 0xf */
printf( "0%o", num ); /* prints 017 (octal) */
num = 017;
printf( "%d", num ); /* prints 15 */
printf( "0x%x", num ); /* prints 0xf */
printf( "0%o", num ); /* prints 017 (octal) */
Integer types in the C language don't really have a base. When you say:
int a = 100;
int b = 0x64;
...both a
and b
have the same value. It doesn't make any sense to talk about converting a
into hexadecimal (or b
into decimal).
100
in decimal is 0x64
in hex, no 'conversion' is needed. The base of an integer is just a matter of interpretation.
Um,
int i = 100;
char c = i; // c now has the value 0x64 (aka decimal 100)
there really isn't anything else you have to do, except be sure that i
isn't larger than 255.
Numeric bases only really come into play when printing or otherwise displaying a number to a human. As far as a number in memory goes, 100 is 0x64 is 0144 is 1100100. They're all the same value, so they all are represented by the same set of bits.
It's like asking how you would display the color green in Spanish. Green is green is green no matter what language you're using. It's only when you try to come up with a way to write it as a word that you have to consider what language you're going to use. So it is with numbers and deciding which base you're going to use.
精彩评论