Skip to content

Instantly share code, notes, and snippets.

@shigeyas
Created October 1, 2009 08:20
Show Gist options
  • Save shigeyas/198825 to your computer and use it in GitHub Desktop.
Save shigeyas/198825 to your computer and use it in GitHub Desktop.
# Converting hexadecimal string (like: '001122deadbeaf')
# into binary string and vice-versa
def binary2hexstring(b)
b.unpack("H*")[0]
end
def hexstring2binary(h)
h.scan(/([0-9a-fA-F][0-9a-fA-F])/).collect{|v| v[0].hex.chr }.join
end
if __FILE__ == $0
require 'test/unit'
class TestBinaryString < Test::Unit::TestCase
def sub1(teststring)
bs = hexstring2binary(teststring)
assert_not_nil(bs)
hs = binary2hexstring(bs)
assert_not_nil(hs)
assert_equal(teststring, hs)
end
def test_run
sub1("000102030405060708090a0b0c0d0e0f")
sub1("36da8ed81ac6dc23c6288117bb4725f9") # some real MD5s
sub1("3e2530cec62f8a898ae3f75c1bb13ada")
sub1("41aa1b20603c0faeaed350b1804e83bd")
sub1("53570e05af1b3dc6e10f1ddec1704b90201f3890") # some real SHA1s
sub1("5e6a4a0cdfc008b0546626b89d7be4abb368e75d")
sub1("bdf5c5558b5354cfc663d366cd0e62591ff9f8c2")
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment