Integer format specifiers control how integer values are represented by printf(). The length modifiers h, l, and ll specify the expected integer type.
#include <stdio.h>
int main()
{
int a = -25;
unsigned int b = 25;
long c = 100000L;
long long d = 1000000000LL;
printf("Decimal : %d\n", a);
printf("Unsigned : %u\n", b);
printf("Octal : %o\n", b);
printf("Hexadecimal : %x\n", b);
printf("Long : %ld\n", c);
printf("Long long : %lld\n", d);
return 0;
}
Example Output #
Decimal : -25
Unsigned : 25
Octal : 31
Hexadecimal : 19
Long : 100000
Long long : 1000000000
Explanation #
The basic integer conversion specifiers are:
| Specifier | Expected type | Representation |
|---|---|---|
%d |
int |
Signed decimal |
%i |
int |
Signed decimal |
%u |
unsigned int |
Unsigned decimal |
%o |
unsigned int |
Octal |
%x |
unsigned int |
Lowercase hexadecimal |
%X |
unsigned int |
Uppercase hexadecimal |
For example:
printf("%x\n", b);
prints the value of b in hexadecimal.
Integer Length Modifiers #
Length modifiers can be combined with conversion specifiers:
| Format | Expected type | Purpose |
|---|---|---|
%hd |
int |
short value |
%hu |
unsigned int |
unsigned short value |
%ld |
long int |
Signed long |
%lu |
unsigned long int |
Unsigned long |
%lld |
long long int |
Signed long long |
%llu |
unsigned long long int |
Unsigned long long |
%lx |
unsigned long int |
Unsigned long in hexadecimal |
%llx |
unsigned long long int |
Unsigned long long in hexadecimal |
For printf(), integer types narrower than int, such as short, undergo integer promotion before being passed as arguments. Therefore %hd still corresponds to the promoted argument type expected by printf, with the h modifier controlling how the value is interpreted for output.
The format specifier must match the argument type expected by the conversion specification. A mismatch can result in undefined behavior.