Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

c - How can I print maximum value of an unsigned integer?

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
",x);
    x=~x;
    printf("%d",x);
    getch();
    return 0;
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
", UINT_MAX, UINT_MAX);
    printf("max      = %u = 0x%x
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...