Last active
August 29, 2015 13:56
-
-
Save wvanbergen/8899809 to your computer and use it in GitHub Desktop.
0xabc to 0xaabbcc using bitwise operators
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
# There must be a nicer way than this | |
((x & 0xf00) << 12 | (x & 0xf00) << 8) | | |
((x & 0x0f0) << 8 | (x & 0x0f0) << 4) | | |
((x & 0x00f) << 4 | (x & 0x00f)) |
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
# I prefer not to do this: | |
x.to_s(16).gsub(/([0-9a-f])/i, '\1\1')).to_i(16) |
Alternatively
input = 0xabc
n = 0
output = 0
while input >= (1 << n)
output |= (input & (0xf << n)) * (0x11 << n)
n += 4
end
puts output.to_s(16)
Even more obfuscated (I may be missing the point)
(0 .. (Math.log2(input)/4).floor).map {|n| n*4}.map {|n| (input & (0xf << n)) * (0x11 << n)}.inject(:|)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the simplest I can think of.
Where I am not really sure if modulo is the fastest way to get the last hex part of an integer.