aspose file tools*
The moose likes Java in General and the fly likes Swapping through shift operators ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Swapping through shift operators ?" Watch "Swapping through shift operators ?" New topic
Author

Swapping through shift operators ?

Iftikhar Arain
Ranch Hand

Joined: Jul 17, 2002
Posts: 95

Can any one tell me how to swap two numbers without using third number with the help of shift operators.
Thanks


SCJP,SCWCD,IBM UML,FLEX & AIR,MCAD,MCSD, Adobe ACE
Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

Swap using shift operators? No clue. The XOR swap is well-known, though...

http://en.wikipedia.org/wiki/Xor_swap_algorithm

Example:
[ September 16, 2005: Message edited by: Steve Morrow ]
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41874
    
  63
If you know that i and j are int (i.e., can be represented in 32 bits), something like the following would do the trick.

long i = 5;
int j = 7;

i = (i << 32) + j;
j = i >> 32;
i = i & 1111111111111111;

I haven't tested it, and it doesn't work with negative numbers, but you get the idea.

Of course, you can just use simple arithmetic:

i = i + j;
j = i - j;
i = i - j;


Ping & DNS - my free Android networking tools app
 
Consider Paul's rocket mass heater.
 
subject: Swapping through shift operators ?