From: Todd Benson Date: 2008-03-10T05:37:20+09:00 Subject: Re: bin2str conversion On Sun, Mar 9, 2008 at 4:41 AM, Arlen Cuss wrote: > Hi, > > On Sun, Mar 9, 2008 at 12:11 PM, Zangief Ief wrote: > > > > I would like to write a function which is able to convert a binary data > > into its string format... > > For example, here I have the opposite of my goal. > > > My apologies, I just got what you meant! How's this? > > celtic@sohma:~$ cat test.rb > class String > def to_binary > self.unpack('C*').map {|x| x.to_s(2).rjust(8, '0')}.join Not sure, but that ^^^^ line seems to be the same as this... unpack('B*').first > end > > def self.from_binary b > b.scan(/.{8}/).map {|x| x.to_i(2)}.pack('C*') I thought I could come up with something better than this, but I guess not right now :-) > end > end > > string = "Hello, world!" > puts binary = string.to_binary > puts String.from_binary(binary) > > celtic@sohma:~$ ruby test.rb > 01001000011001010110110001101100011011110010110000100000011101110110111101110010011011000110010000100001 > Hello, world! > celtic@sohma:~$ > > HTH, > Arlen. Todd