cbit-manipulationpuzzle

In c binary, testing to see if a number is in range


This is part of a puzzle that I can't figure out. The function takes in three inputs. The first is an int, the second is the lower bound and the third is the upper bound. I need to test to see if that first number is within the lower and upper bound inclusive.

If it is in range then return 1, else return 0. The catch is that I can only use

! ~ & ^ | + << >> 

operations and only a combination of 20 of them.. Also, only int variables may be used, and no if statements, loops or function calls.

Range(int x, int lower, int upper){
//... some code here
return retVal;
}

Obviously I understand the logic here. If((x >= lower) && (x <= upper)) return 1; The only problem is that I can't use if statements, <, >, ==, or &&.


Solution

  • I'm liking these puzzles you have! For this you will want to have something like,

    Ok to be abstract on this one, you will want to have 2 variables.

    The first variable (lets call it blarg) you need to set the upper bound and add the flipped x. Now you will want to add one to blarg and flip it.

    Your second variable (lets call it hold) will add the x to the flipped lower bound; After that add 1 to hold and flip it too.

    set blarg = to the blarg plus hold; shift blarg over 31 to the the right. and AND it with 1.

    Should be what you are looking for.