Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I print maximum value of an unsigned integer?

Tags:

c

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?

like image 573
SHRI Avatar asked Oct 10 '12 05:10

SHRI


People also ask

How do you find the maximum value of an unsigned int?

To find the max value for the unsigned integer data type, we take 2 to the power of 16 and substract by 1, which would is 65,535 . We get the number 16 from taking the number of bytes that assigned to the unsigned short int data type (2) and multiple it by the number of bits assigned to each byte (8) and get 16.

How do I print an unsigned integer?

An unsigned Integer means the variable can hold only a positive value. This format specifier is used within the printf() function for printing the unsigned integer variables. printf(“%u”, value);

What is the maximum range of unsigned integer datatype?

An unsigned integer is a 32-bit datum that encodes a nonnegative integer in the range [0 to 4294967295]. The signed integer is represented in twos complement notation. The most significant byte is 0 and the least significant is 3.


3 Answers

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.

like image 194
Syed Avatar answered Oct 03 '22 04:10

Syed


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.

like image 21
Keith Thompson Avatar answered Oct 03 '22 03:10

Keith Thompson


Use %u as the printf format string.

like image 33
Musa Avatar answered Oct 03 '22 04:10

Musa