Forums Register Login

Swapping through shift operators ?

+Pie Number of slices to send: Send
Can any one tell me how to swap two numbers without using third number with the help of shift operators.
Thanks
+Pie Number of slices to send: Send
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 ]
+Pie Number of slices to send: Send
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;
Don't destroy the earth! That's where I keep all my stuff! Including this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1516 times.
Similar Threads
Adding the values without using arithmentic operators
Is shift operators covered in 1.5 exam?
Logical operators in "Section 4: Algorithm Design and Implementation"
shift operators
need tips and tricks/link on shift parameters
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 10:46:14.