Problems with bitwise operators

Please support our C advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Feb 2005
Posts: 2
Reputation: scrapper777 is an unknown quantity at this point 
Solved Threads: 0
scrapper777 scrapper777 is offline Offline
Newbie Poster

Problems with bitwise operators

 
0
  #1
Feb 28th, 2005
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!
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,858
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 755
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Senior Bitch

Re: Problems with bitwise operators

 
0
  #2
Feb 28th, 2005
Are you sure it should accept negative numbers? The bitwise operators are tricky when working with signed types.
New members chased away this month: 5
Reply With Quote Quick reply to this message  
Join Date: Feb 2005
Posts: 2
Reputation: scrapper777 is an unknown quantity at this point 
Solved Threads: 0
scrapper777 scrapper777 is offline Offline
Newbie Poster

Re: Problems with bitwise operators

 
0
  #3
Feb 28th, 2005
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.
Reply With Quote Quick reply to this message  
Join Date: Feb 2005
Posts: 199
Reputation: Tight_Coder_Ex is an unknown quantity at this point 
Solved Threads: 14
Tight_Coder_Ex's Avatar
Tight_Coder_Ex Tight_Coder_Ex is offline Offline
Junior Poster

Re: Problems with bitwise operators

 
0
  #4
Feb 28th, 2005
try
  1. ((x + ~y) >> 31) & 1
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 4409 | Replies: 3
Thread Tools Search this Thread



Tag cloud for C
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC