bodacydo
bodacydo

Reputation: 79549

How to printf "unsigned long" in C?

I can never understand how to print unsigned long datatype in C.

Suppose unsigned_foo is an unsigned long, then I try:

And all of them print some kind of -123123123 number instead of unsigned long that I have.

Upvotes: 476

Views: 1010146

Answers (7)

Linkon
Linkon

Reputation: 1168

For int %d

For long int %ld

For long long int %lld

For unsigned long long int %llu

Upvotes: 64

Kumar Alok
Kumar Alok

Reputation: 2612

The correct specifier for unsigned long is %lu.

If you are not getting the exact value you are expecting then there may be some problems in your code.

Please copy your code here. Then maybe someone can tell you better what the problem is.

Upvotes: 17

Praveen S
Praveen S

Reputation: 10393

The format is %lu.

Please check about the various other datatypes and their usage in printf here

Upvotes: 14

NealCaffery
NealCaffery

Reputation: 562

  • %lu for unsigned long
  • %llu for unsigned long long

Upvotes: 45

Sanjith Bravo Dastan
Sanjith Bravo Dastan

Reputation: 449

int main()
{
    unsigned long long d;
    scanf("%llu",&d);
    printf("%llu",d);
    getch();
}

This will be helpful . . .

Upvotes: 11

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215607

Out of all the combinations you tried, %ld and %lu are the only ones which are valid printf format specifiers at all. %lu (long unsigned decimal), %lx or %lX (long hex with lowercase or uppercase letters), and %lo (long octal) are the only valid format specifiers for a variable of type unsigned long (of course you can add field width, precision, etc modifiers between the % and the l).

Upvotes: 26

Thanatos
Thanatos

Reputation: 44354

%lu is the correct format for unsigned long. Sounds like there are other issues at play here, such as memory corruption or an uninitialized variable. Perhaps show us a larger picture?

Upvotes: 684

Related Questions