Pages

11/10/2011

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
"Hello".unpack("B*")
=> ["0100100001100101011011000110110001101111"]

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

The output is in array format, removing an array can be done by adding [0] to select the first element from array.
"Hello".unpack("B*")[0]
=> "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.
‎"Hello".unpack("C*")
=> [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
a="0100100001100101011011000110110001101111"
[a].pack("B*")
=> "Hello"

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



P.S.
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
["Hello"].pack("m*").chomp
=> "SGVsbG8="
Base64 Decoding
"SGVsbG8=".unpack("m*")[0]
=> "Hello"

1 comment: