Find if X is between A and B by bit-wise operators

How can I find if an integer X is between integer A and B by using bit-wise operators?

We need to determine A < X < B then,

  • A-X < 0
  • B-X > 0

#include<stdio.h>
#define CHAR_BIT 8
int main()
{
int a,b,x,amx,bmx,sign_amx,sign_bmx;
scanf("%d %d %d",&a,&b,&x);
amx=a-x;
bmx=b-x;
if(!bmx) // If B-X = 0 then make bmx negative
    bmx=-1; // to exclude upper limit
sign_amx = 0 | (amx >> (sizeof(int) * CHAR_BIT - 1)); // if amx<0 then sign_amx is -1 else 0
sign_bmx = 0 | (bmx >> (sizeof(int) * CHAR_BIT - 1)); // if bmx<0 then sign_amx is -1 else 0
if(sign_amx && !sign_bmx)
    printf("Yes!!");
else
    printf("No!!");
return 0;
}

[Alternate]We need to determine A < X < B then,

  • A-X < 0
  • B-X > 0

#include<stdio.h>
#define CHAR_BIT 8
int main()
{
int a,b,x,amx,bmx,sign;
scanf("%d %d %d",&a,&b,&x);
amx=a-x;
bmx=b-x;
if(!bmx) // If B-X = 0 then make bmx negative
    bmx=-1; // to exclude upper limit
sign = 0 | ((amx^bmx) >> (sizeof(int) * CHAR_BIT - 1));
if(sign)
    printf("Yes!!");
else
    printf("No!!");
return 0;
}

ANSWERS GIVEN ABOVE ARE GREAT but here are some links to get you strong at concepts

3 Likes

why would you do so ?

Can we use arithmetic operators(+,-)??