How can I print maximum value of an unsigned integer?

7

I want to print the maximum value of the unsigned integer which is of 4 bytes.

#include "stdafx.h"
#include "conio.h"

int _tmain(int argc, _TCHAR* argv[])
{
    unsigned int x = 0xffffffff;
    printf("%d\n",x);
    x=~x;
    printf("%d",x);
    getch();
    return 0;
}

But I get output as -1 and 0. How can I print x = 4294967295?

c
asked on Stack Overflow Oct 10, 2012 by SHRI • edited Feb 12, 2019 by grooveplex

8 Answers

14

Use %u as the printf format string.

answered on Stack Overflow Oct 10, 2012 by Musa
14

The %d format treats its argument as a signed int. Use %u instead.

But a better way to get the maximum value of type unsigned int is to use the UINT_MAX macro. You'll need

#include <limits.h>

to make it visible.

You can also compute the maximum value of an unsigned type by converting the value -1 to the type.

#include <limits.h>
#include <stdio.h>
int main(void) {
    unsigned int max = -1;
    printf("UINT_MAX = %u = 0x%x\n", UINT_MAX, UINT_MAX);
    printf("max      = %u = 0x%x\n", max, max);
    return 0;
}

Note that the UINT_MAX isn't necessarily 0xffffffff. It is if unsigned int happens to be 32 bits, but it could be as small as 16 bits; it's 64 bits on a few systems.

answered on Stack Overflow Oct 10, 2012 by Keith Thompson
6

There is the macro defined in <limits.h>: UINT_MAX.

answered on Stack Overflow Oct 10, 2012 by FamZheng
4

Use %u as the format string to print unsigned int, %lu for unsigned long, and %hu for unsigned short.

answered on Stack Overflow Oct 10, 2012 by nneonneo
3

You should use <stdint.h> and <limits.h> then INT_MAX or whatever limit is appropriate for your type.

1

printf("%u", ~0); //fills up all bits in an unsigned int with 1 and prints the value.

answered on Stack Overflow Nov 15, 2013 by Nikhil
1

Curious and easy way to do this is just

printf("%lu",-1);

it prints whatever the biggest unsigned in your computer:)

answered on Stack Overflow Feb 11, 2019 by hikmat_11 • edited Feb 12, 2019 by hikmat_11
1

Here is the code:

#include <stdio.h>

int main(void) {
    unsigned int a = 0;
    printf("%u", --a);
    return 0;
}

Output:

4294967295

How it works is that 0 is the minimum value for unsigned int and when you further decrease that value by 1 it wraps around and moves to the highest value.

answered on Stack Overflow Feb 12, 2019 by Syed

User contributions licensed under CC BY-SA 3.0