Convert String to Binary in Ruby

As for the sake of today 11/11/11,
Everything is in binary mode.
Why not do a conversion between String and binary :)

Conversion from String to binary
Easiest way, using unpack and tell Ruby that it is binary
=> ["0100100001100101011011000110110001101111"]

You can specify length of each binary by replace * with total length of the word (default binary has 8 bit per character)
=> ["0100100001100101011011000110110001101111"]

The output is in array format, removing an array can be done by adding [0] to select the first element from array.
=> "0100100001100101011011000110110001101111"

Other method is to break down the string into characters first and get ASCII number of each character, then convert them to binary.
Here is a way for breaking a String into ASCII character code.
=> [72, 101, 108, 108, 111]

Then using print formatting with %b to convert each ASCII code (int) to binary
"Hello".unpack("C*").each{|c| print "%08b" % c}

Another way to do using split('')
"Hello".split('').each{|c| print "%08b" % c[0] }
=> 0100100001100101011011000110110001101111

Or you could use scan(/./)
"Hello".scan(/./).each{|c| print "%08b" % c[0] }
=> 0100100001100101011011000110110001101111

Actually there is another method for converting number into binary, it is using ".to_str(2)" but this method doesn't put leading-zeros in the result, as you can see:
"Hello".scan(/./).each{|c| print "%08s " % c[0].to_s(2) }
=> 1001000 1100101 1101100 1101100 1101111

Conversion from binary back to String
Same as above, we can use the same method to convert binary back to String
=> "Hello"

Or split it by 8 digit each, then convert each 8 digit to int , then to character
(0..a.length).step(8).each {|i| print a[i,8].to_i(2).chr}
=> Hello

After reading .pack and .unpack function API, I found that Ruby has a built-in Base64 encoder/decoder.
To use it just use pack() or unpack() with "m" directive
Base64 Encoding
=> "SGVsbG8="
Base64 Decoding
=> "Hello"


  1. The logic used in the code is very impressive and gives effective results. Ruby resources are plentiful and it contains over 60,000 libraries that's why I recommend it to all the beginners. Ruby is really easy to use and implement. Looking forward to visit this kind of stuff in the future.