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)
@barttenbrinke
Copy link

This is the simplest I can think of.

input = 0xabc
pointer = 0x0
output = 0x0

while input > 0
  hexchunk = input % 16
  input /= 16

  part1 = (hexchunk << pointer*4)
  part2 = (hexchunk << (pointer+1)*4)

  output = output | part1 | part2
  pointer += 2
end

puts output.to_s(16)

aabbcc 

Where I am not really sure if modulo is the fastest way to get the last hex part of an integer.

@snoble
Copy link

snoble commented Feb 9, 2014

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)

@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