From: Melissa Silas Date: 2007-06-19T00:17:38+09:00 Subject: Re: healp reading / writing binary strings. Robert Klemme wrote: > On 18.06.2007 03:52, Melissa Silas wrote: >> What exactly kind of format is that? > Um, how can we know what format this is? I mean, you came up with that > string. The definition above just uses octal escapes. You can as well > have hex codes: > > irb(main):013:0> "\x21\x20\x40" > => "! @" > > > How do I parse it / read binary >> data from it? > > Depends on what you want to do with it. If you want to access bytes you > can simply do this > > irb(main):014:0> s = "\t\001" > => "\t\001" > irb(main):015:0> s[0] > => 9 > irb(main):016:0> s[1] > => 1 > > If you want bits you can do > > irb(main):017:0> s.unpack "b*" > => ["1001000010000000"] > irb(main):018:0> s.unpack "b8b8" > => ["10010000", "10000000"] > irb(main):019:0> s.unpack "b4*" > => ["1001"] > irb(main):020:0> s.unpack "b4b4b4b4" > => ["1001", "1000", "", ""] > irb(main):021:0> s.unpack "b4b4b" > => ["1001", "1000", ""] > irb(main):022:0> s.unpack "b4b4" > => ["1001", "1000"] > > Please see #unpack docs for more info. > > > And how can I write the same type of string from say an >> array? ["foo","bar"]? > > "Write from an array"? I don't understand what you mean. If you want to > put it into an array, you can simply do > > irb(main):023:0> ["foo", "\tbar\n"] > => ["foo", "\tbar\n"] > > Kind regards > > robert Thanks that helps.. Couple more questions.. for this example: s = "\t\001" puts s[0] -> 9 How does \t come out as 9? Is that the tab char which in turn is the number 9 in ascii table? for this example: s = "\001" Ok so now I know this is octal, does the octal value I supply correspond to the ascii table as well? for this example: s = "\x01" for hex, does the hex value I supply correspond to the ascii table as well? Thanks for the help. This is helping me understand this a bunch.. -Melissa -- Posted via http://www.ruby-forum.com/.