HOME       >>       Programming

Last Bitwise Problem


I'm working on a bitwise problem where I can't use loops or logical operators. I need to return 1 ix x<y else return 0. The valid operators that I can use are ! ~ & ^ | + << >>My code that isn't working so far is:/* isLess - if x < y then return 1, else return 0* Example: isLess(4,5) = 1.* Legal ops: ! ~ & ^ | + << >>* Max ops: 24*/int isLess(int x, int y) {return ((x + (~y + 1)) >> 31 ) ;}It seems to have problems with the negative numbers.Going insane!


Wow, I miss the C++ forums for some weeks, and see the changes! Alright, let's see.By ops you mean operations as in statement; not uops right? (assembly stuff) 'Cause otherwise it's crazy. I'm assuming you're talking about 2's complement negatives from your code . It seems your problem is that your code does NOT account for negative numbers. Example:int x = 4; int y = -5return ((x + (~y + 1)) >> 31 ) ;/*Dev-C++ defines int in the range of -32768 to +32767, therefore : */-> return ((4 + (~5 + 1)) >> 31;-> return (4 + -5) >> 31;-> return -1 >> 31;-> return 1;so 4 is less than -5 that's ok, I do the same thing at times. I'll get the answer to you when I think of it.


I am new to this forum. I was hanging around this c,c++ section for a while and found this question pretty interesting.i have a code sample which i feel can do what is expected.bugs and comments are welcomeint fun1(int num1 ,int num2){int temp1 ,temp2;//if(num1 < num2)//return 1//else//return 0if(num1 >> 31){ if(!(num2 >> 31)) return 1; temp1 = ~(num1 + 0xFFFFFF); temp2 = ~(num2 + 0xFFFFFF); if((~temp2) & temp1) return 1; else return 0;}if((~num1) & num2)return 1;elsereturn 0;}hope this code work for all possible valuesbyessv


Hello ssv, I tested your sample on Dev-C++ (since I was too lazy to study it) using a range of 0 to 512 and using x and x-1 as parameters of your function.

Here's what it returned:
num1 num2 fun1()
0 -1 1 //ok, good so far
1 0 0 //
2 1 1
3 2 0
4 3 1
5 4 0
6 5 1 //ok, I get the picture now...

ad 512... hmm... seems like a odd/even test. Sorry. It looks like you went great depths trying this one. Good try though. By the way, I haven't found a solution myself.

Remember, kvarnerexpress stated that we can't use logical operators, so the if's and else's have to go if you want to declare it a solution.

Here's my test code:

//uses iostream and fstreamint main(){    std::ofstream file("testfile");    int x = 0;    while (x!=512)    {     file << fun1(x,x-1) << "\n";     x++;    }    return 0;}


Xisto.com offers Free Web Hosting to its Members for their participation in this Community. We moderate all content posted here but we cannot warrant full correctness of all content. While using this site, you agree to have read and accepted our terms of use, cookie and privacy policy. Copyright 2001-2019 by Xisto Corporation. All Rights Reserved.