File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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.

Steve Morrow
Ranch Hand

Joined: May 22, 2003
Posts: 657

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

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

Joined: Mar 22, 2005
Posts: 42965
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;
I agree. Here's the link:
subject: Swapping through shift operators ?
It's not a secret anymore!