×

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

 0 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 0★mokaddim 2●1●1●2 accept rate: 0% why would you do so ? (09 Apr '12, 03:10) Can we use arithmetic operators(+,-)?? (12 Apr '12, 18:02) chirayu2★

 3 ANSWERS GIVEN ABOVE ARE GREAT but here are some links to get you strong at concepts https://en.wikipedia.org/wiki/Bitwise_operation http://www.toves.org/books/bitops/ http://www.geeksforgeeks.org/interesting-facts-bitwise-operators-c/ answered 23 Sep '15, 13:40 585●4●14 accept rate: 8%
 0 We need to determine A < X < B then, A-X < 0 B-X > 0 #include #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; }  answered 12 Apr '12, 18:42 2★chirayu 16●1●1●4 accept rate: 0%
 0 [Alternate]We need to determine A < X < B then, A-X < 0 B-X > 0 #include #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; }  answered 12 Apr '12, 18:53 2★chirayu 16●1●1●4 accept rate: 0%
 toggle preview community wiki:
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• 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