Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting binary data to string in ruby

Tags:

ruby

I have a string containing byte data.
How can I perform an in-place conversion to ascii string?

like image 655
LK. Avatar asked Feb 05 '09 11:02

LK.


3 Answers

You can do so via using base64 which is a fairly universal way.

require 'base64'

str = Base64.encode64(data)
like image 107
Philip Reynolds Avatar answered Sep 19 '22 20:09

Philip Reynolds


if u have a binary string lets say something like:

s = "01001101011011110111000101110101011001010110010101110100"

and u wanna convert it back to ascii text in Ruby u can do like:

s = "01001101011011110111000101110101011001010110010101110100"

(0..s.length-8).step(8) do |i|
    print s[i,8].to_i(base=2).chr
end

Hope this will help someone :)

like image 31
Abdul.Moqueet Avatar answered Sep 22 '22 20:09

Abdul.Moqueet


Another way to play with binary data is String#unpack.

like image 20
Keltia Avatar answered Sep 19 '22 20:09

Keltia