How to display hexadecimal numbers in C?

CFormatIntegerPrintfHex

C Problem Overview


I have a list of numbers as below:

> 0, 16, 32, 48 ...

I need to output those numbers in hexadecimal as:

> 0000,0010,0020,0030,0040 ...

I have tried solution such as:

printf("%.4x",a); // where a is an integer

but the result that I got is:

> 0000, 0001, 0002, 0003, 0004 ...

I think I'm close there. Can anybody help as I'm not so good at printf in C.

Thanks.

C Solutions


Solution 1 - C

Try:

printf("%04x",a);
  • 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified.
  • 4 (width) - Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is right justified within this width by padding on the left with the pad character. By default this is a blank space, but the leading zero we used specifies a zero as the pad char. The value is not truncated even if the result is larger.
  • x - Specifier for hexadecimal integer.

More here

Solution 2 - C

i use it like this:

printf("my number is 0x%02X\n",number);
// output: my number is 0x4A

Just change number "2" to any number of chars You want to print ;)

Solution 3 - C

Your code has no problem. It does print the way you want. Alternatively, you can do this:

printf("%04x",a);

Solution 4 - C

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser188276View Question on Stackoverflow
Solution 1 - CcodaddictView Answer on Stackoverflow
Solution 2 - CzeiljaView Answer on Stackoverflow
Solution 3 - CloxxyView Answer on Stackoverflow
Solution 4 - ChmofradView Answer on Stackoverflow