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?
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.
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);
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.
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.
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.
Use %u
as the printf format string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With