Created
April 30, 2016 18:08
-
-
Save luisalima/bfe722aa031d2ac05fb124b2c599ce6f to your computer and use it in GitHub Desktop.
Bit manipulation in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# swapping two integers, without using a temporary variable | |
a = 5 # 5 | |
b = 7 # 7 | |
a.to_s(2) # "101" | |
b.to_s(2) # "111" | |
a ^= b # a is now "010" | |
b ^= a # b is now "101" | |
a ^= b # a is now "111" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I stumbled upon this. In Ruby you can also do: