C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Programming Tips & Tricks » C - Tips & Tricks

Print maximum value of an unsigned int using One's Compliment (~) Operator in C

By: IncludeHelp, on 31 JAN 2017

In "An amazing trick to print maximum value of an unsigned integer in C" I have discussed we can find maximum value of an unsigned int by assigning -1 to the variable. Here I am with another trick to get maximum value of an unsigned int using One's Compliment [Bitwise NOT Operator (~)] in C language.

Follow the given steps:

Step 1: Declare an unsigned int variable.

Step 2: Assign it with 0 (or 0x00 in Hexadecimal).

unsigned int max_val;
max_val=0x00;

Step 3: Do One’s Compliment.

max_val = ~max_val;

Step 4: Print the value with %u format specifier.






Consider the following example:

#include <stdio.h>
int main()
{
	unsigned int max_val;
	max_val=0x00;
	
	//one's compliment
	max_val = ~max_val;
	printf("max_val: %X (Decimal value: %u)\n",max_val,max_val);
	
	return 0;
}

Output

max_val: FFFFFFFF (Decimal value: 4294967295)

Explanation

As I discussed in Bitwise NOT Operator (~) that Bitwise NOT Operator toggle (flips) all bits for 0 to 1 and 1 to 0, here initial value is 0x00000000 (Binary: 00000000000000000000000000000000) and after One's Compliment (~max_val) the value will be 0xFFFFFFFF (Binary: 11111111111111111111111111111111), that is the maximum value of an unsigned integer.


COMMENTS