Skip to content

Instantly share code, notes, and snippets.

@wvanbergen
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wvanbergen/8899809 to your computer and use it in GitHub Desktop.
Save wvanbergen/8899809 to your computer and use it in GitHub Desktop.
0xabc to 0xaabbcc using bitwise operators
# 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))
# I prefer not to do this:
x.to_s(16).gsub(/([0-9a-f])/i, '\1\1')).to_i(16)
@snoble
Copy link

snoble commented Feb 9, 2014

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