Skip to content

Instantly share code, notes, and snippets.

@wvanbergen

wvanbergen/bitwise.rb

Last active Aug 29, 2015
Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@barttenbrinke barttenbrinke commented Feb 9, 2014

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

This comment has been minimized.

Copy link

@snoble 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

This comment has been minimized.

Copy link

@snoble 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