How to Find Max & Min of Two Numbers without using Conditional Operator in C

#include "stdafx.h"
#include <stdio.h>
#include <conio.h>

int clearMSBthroughI(int num, int i) {
    int mask = (1 << i) - 1;
    return num & mask;

// To clear all bits from i through 0 (inclusive), we do:
int clearBitsIthrough0(int num, int i) {
    int mask = ~((1 << (i+1)) - 1);
    return num & mask;

int _tmain(int argc, _TCHAR* argv[])
    int x = 0xCCCC;  // we want to find the minimum of x and y
    int y = 0x7777;
    int r;  // the result goes here

    r = y ^ ((x ^ y) & -(x < y)); // min(x, y)
    printf("Min: %x\n",r);

    r = X ^ ((x ^ y) & -(x < y)); // max(x, y)
    printf("Max: %x\n",r);

    int ans1 = clearBitsIthrough0(0x77, 3);
    int ans2 = clearMSBthroughI(0xFF, 3);

    printf("Ans1: %x & Ans2 = %x\n",ans1, ans2);

    return 0;



Min: 7777

Ans1: 70 & Ans2 = 7

Related Post:

Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault ?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Unknown

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment


Post a Comment

Related Posts Plugin for WordPress, Blogger...