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 and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.