w3resource

Conversion Specifier for Printing long in C with printf

Conversion Specifier for Printing long in C with printf

In C programming, the printf function allows you to format output based on various data types. When working with long integers, a specific conversion specifier is required to print them correctly. The long type is typically used to store larger integers, and printf provides specifiers to handle this data type accurately.

Conversion Specifier for long in printf

For printing a long integer, you use the %ld specifier. This specifier tells printf to format the corresponding argument as a long int. For unsigned long values, use %lu.

List of long Conversion Specifiers

  • %ld: For long int
  • %lu: For unsigned long int
  • %lx or %lX: For unsigned long int in hexadecimal format (lowercase and uppercase)
  • %lo: For unsigned long int in octal format

Examples of Formatting long in printf:

Example 1: Using %ld for long int

In this example, %ld formats the long integer value stored in num and displays it.

Code:

#include <stdio.h> 
int main() {
    long num = 1234567890;
    printf("The long integer is: %ld\n", num);
    return 0;
}

Output:

The long integer is: 1234567890

Example 2: Using %lu for unsigned long int

Here, %lu is used for unsigned long, which displays the unsigned integer.

Example: Positional Initialization

Code:

#include <stdio.h> 
int main() {
    unsigned long num = 1234567890UL;
    printf("The unsigned long integer is: %lu\n", num);
    return 0;
}

Output:

The unsigned long integer is: 1234567890

Example 3: Using %lx for Hexadecimal Representation

The %lx specifier formats the unsigned long integer as a hexadecimal.

Code:

#include <stdio.h> 
int main() {
    unsigned long hexNum = 1234567890UL;
    printf("The unsigned long integer in hexadecimal: %lx\n", hexNum);
    return 0;
}

Output:

The unsigned long integer in hexadecimal: 499602d2

Summary:

The printf function in C provides %ld, %lu, %lx, and %lo for formatting long integers in various representations, such as decimal, hexadecimal, and octal. Using the correct specifier ensures that long integers are displayed accurately.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming-exercises/c-snippets/conversion-specifier-for-formatting-long-with-printf-in-c.php