[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1770
  • Last Modified:

bitwise isgreater help

i can't seem to get this to work.  It always returns the opposite of what i want.. ideas?

(i'd only like to use bitwise operators)
/*
 * isGreater - if x > y  then return 1, else return 0
 */
int isGreater(int x, int y) {
int val1 = !(x >> 31) & (y >> 31);
int val2 = !(x >> 31 ^ y >> 31);
int val3 = ((y + x + 1) >> 31);
int val4 = (val1 | val2) & val3;
return (!!(val4^0));
}
/*

Open in new window

0
braker15
Asked:
braker15
  • 3
2 Solutions
 
ZoppoCommented:
Hi braker15,

I didn't really analyze the function, but this IMO is senseless:
> return (!!(val4^0));

Here you use the !-operator two times which is the same as if you didn't use it at all.

ZOPPO
0
 
Infinity08Commented:
Using signed ints with shift operators (more specifically right shift operators) is not recommended, unless you know how they work. Use unsigned ints instead.

I take it you verified that on your system, an int is 32 bits wide, has 31 value bits, and 1 sign bit ? If not, you should verify that, and mark the code as platform-dependent.


>> (i'd only like to use bitwise operators)

You're using arithmetic operators (+) and boolean operators (!) too ... Is that ok ?


>>  It always returns the opposite of what i want..

Well, take x = 2 and y = 1, and see what each of the temporary values is set to ... Is that what you intended ? Can you see where it goes wrong ?
0
 
Infinity08Commented:
May I ask why you gave a B grade ? That usually means that something was missing in the answer and/or that something is still unclear. If that's the case, then please do not hesitate to ask for clarification where needed.
0
 
braker15Author Commented:
infinity:

because I still never got a reason for why the result was always the opposite of what I wanted.
0
 
Infinity08Commented:
>> because I still never got a reason for why the result was always the opposite of what I wanted.

Why didn't you ask about that then ? We can't know what more information you still need, if you don't tell us.

The reason for why it doesn't give you the result you expect, is because the code does something else :) If you go through the code using the example I posted, it should be clear.
You need to fix the code to make it do what you want.

Did you also take into account all of the advice given ?
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now