944,038 Members | Top Members by Rank

Ad:
  • C Discussion Thread
  • Unsolved
  • Views: 6639
  • C RSS
Feb 28th, 2005
0

Problems with bitwise operators

Expand Post »
Hi,
I am having problem with the following code.This is on a 32 bit system. The problem statement is:
/* isLess - if x < y then return 1, else return 0
* Example: isLess(4,5) = 1.
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 24
*/

I can't use any loops or - * / !! || < >

My code so far is:

int isLess(int x, int y) {

return (( x + (~y + 1)) >> 31 ) & 1 ;

}


It works for all numbers except for negative numbers:

Test isLess(2147483646[0x7ffffffe],-2[0xfffffffe]) failed.
Gives 1[0x1]. Should be 0[0x0]

I am new to programming and am very green when it comes to the negative numbers!

Any help is appreciated!
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
scrapper777 is offline Offline
2 posts
since Feb 2005
Feb 28th, 2005
0

Re: Problems with bitwise operators

Are you sure it should accept negative numbers? The bitwise operators are tricky when working with signed types.
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004
Feb 28th, 2005
0

Re: Problems with bitwise operators

Yes, it is suppose to work with negative numbers too...I'm assuming that is the challenging part. I've had to do 15 of these "puzzles" and this was the last one. I dream 1's and 0's now!

I can't figure out how to get the negative ones to work though.
Reputation Points: 10
Solved Threads: 0
Newbie Poster
scrapper777 is offline Offline
2 posts
since Feb 2005
Feb 28th, 2005
0

Re: Problems with bitwise operators

try
  1. ((x + ~y) >> 31) & 1
Reputation Points: 47
Solved Threads: 17
Posting Whiz in Training
Tight_Coder_Ex is offline Offline
215 posts
since Feb 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C Forum Timeline: declaration of array issue
Next Thread in C Forum Timeline: Error message help





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC