You are not logged in. Please login at www.codechef.com to post your questions!

×

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?

asked 07 Apr '12, 11:16

mokaddim's gravatar image

0★mokaddim
2112
accept rate: 0%

why would you do so ?

(09 Apr '12, 03:10) cyberax ♦3★

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

(12 Apr '12, 18:02) chirayu2★

link

answered 23 Sep '15, 13:40

goyal_banna's gravatar image

3★goyal_banna
585414
accept rate: 8%

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;
}
link

answered 12 Apr '12, 18:42

chirayu's gravatar image

2★chirayu
16114
accept rate: 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;
}
link

answered 12 Apr '12, 18:53

chirayu's gravatar image

2★chirayu
16114
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported
  • mathemetical formulas in Latex between $ symbol

Question tags:

×15
×12
×1

question asked: 07 Apr '12, 11:16

question was seen: 1,746 times

last updated: 23 Sep '15, 13:40