From: Robert Klemme Date: 2007-06-18T15:55:01+09:00 Subject: Re: healp reading / writing binary strings. On 18.06.2007 03:52, Melissa Silas wrote: > Hey, I'm looking for some help with reading / writing binary string. > Just need some help understanding what exactly is going on.. > > if I have a string like: > str = "\t\005\001\006\afoo\006\abar" > > Or if I have something like: > str = > "\t\025\001\004\001\004\002\004\003\004\004\004\005\004\006\004\a\004\b\004\t\004\n" > > 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