• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

Swapping through shift operators ?

 
Ranch Hand
Posts: 95
Spring Flex Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Can any one tell me how to swap two numbers without using third number with the help of shift operators.
Thanks
 
Ranch Hand
Posts: 657
Spring VI Editor Clojure
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 will suppress my every urge. But not this shameless plug:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic