Shortest hex2bin in ruby?

2020-07-24 06:41发布

问题:

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

class
  def hex2bin

  end
end

"AB12345678".hex2bin

回答1:

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

"AB12345678".hex2bin #=> "\xAB\x124Vx"


回答2:

def hex2bin
  [self].pack "H*"
end

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



标签: ruby binary hex