Hey guys just wondering how i can print a hexadecimal using printf
This is a discussion on printf hex within the C Programming forums, part of the General Programming Boards category; Hey guys just wondering how i can print a hexadecimal using printf...
Hey guys just wondering how i can print a hexadecimal using printf
Next time, why don't you read some documentation before posting such a question?Code:/* har har */ int a = 0x09; /* 9 (hex) */ printf("%d", a); /* outputs 9 (hex) */
http://www.google.com/search?q=printf+hexadecimal
You can try %X also. Try it too...
LGIK wins!!!
![]()
Salutes from logicwonder
Enjoy programming
As with all printf() formatting, you use the correct format template specifier. In the case of hexadecimal, you can use either "%x" or "%X", depending on whether you want the alpha digits to be upper or lower case. To get a particular width, with zero padding on the left, you use something like "%08x" (assuming that you want to print the value as an 8 digit hexadecimal number).
For example:Code:#include <stdio.h> #include <stdlib.h> int main(int argc, char **argv) { long octval; char *octend; long decval; char *decend; long hexval; char *hexend; if (argc == 2) { octval = strtol(argv[1], &octend, 8); /* read as octal */ decval = strtol(argv[1], &decend, 10); /* read as decimal */ hexval = strtol(argv[1], &hexend, 16); /* read as hexadecimal */ printf("The string '%s' can be interpreted thus:\n", argv[1]); printf(" Oct: %011o (dec %d, hex %08x, %d chars)\n", octval, octval, octval, (int)(octend - argv[1])); printf(" Dec: %d (oct %011o, hex %08x, %d chars)\n", decval, decval, decval, (int)(decend - argv[1])); printf(" Hex: %08x (oct %011o, dec %d, %d chars)\n", hexval, hexval, hexval, (int)(hexend - argv[1])); } else { printf("Usage: %s valuestring\n", argv[0]); } return 0; }
Insert obnoxious but pithy remark here
I think your reply is a bit confusing.Originally Posted by cwr
I think the original OP is looking how to print out the hex value, as shown by other posters you can use the %x modifier.Code:int a = 0x0a; printf("%d",a); /* outputs 10 (decimal) printf("0x%x",a); /* outputs 0xa */
Last edited by slcjoey; 01-04-2006 at 12:15 PM.
Originally Posted by slcjoey
duh. lol
did you notice the "har har" comment?![]()
Registered Linux User #380033. Be counted: http://counter.li.org