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"

6 comments:

  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.

    ReplyDelete
  2. Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. amethyst rings

    ReplyDelete
  3. I appreciate everything you have added to my knowledge base.Admiring the time and effort you put into your blog and detailed information you offer.Thanks. garnet jewelry

    ReplyDelete
  4. Nice one for taking a few minutes to talk about this amazing, I think highly concerning it as well as absolutely love browsing regarding the issue. Any time prospects, because you gain skill, what views posting to the journal by having added data? This is very helpful for everyone. Amethyst Rings

    ReplyDelete
  5. What a fantabulous post this has been. Never seen this kind of useful post. I am grateful to you and expect more number of posts like these. Thank you very much. Dominoqq online


    ReplyDelete