2

Whats the shortest way to convert hex string to binary string in ruby? for example:

class
  def hex2bin

  end
end

"AB12345678".hex2bin
c2h2
  • 11,911
  • 13
  • 48
  • 60

2 Answers2

3
class String
  def hex2bin
    scan(/../).map { |x| x.to_i(16).chr }.join
  end
end

"AB12345678".hex2bin #=> "\xAB\x124Vx"
Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
  • 2
    you can also do `chars.each_slice(2).map { |x| x.join.to_i(16).chr }.join` which is a bit longer, but likely more efficient because it does not use a regex to extract the char pairs. – Theo Mar 10 '11 at 06:07
2
def hex2bin
  [self].pack "H*"
end

Just found out the pack() function, I think this also works!

c2h2
  • 11,911
  • 13
  • 48
  • 60