Forum: Ruby byte array to string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Jim B. (Guest)
on 2007-02-19 20:10
I'm sure the must be code for this already without me having to go
through the array byte by byte.

I have an array of bytes, I need to print this as a string?

Note the array does not contain text.

Thanks,
Jim
Austin Z. (Guest)
on 2007-02-19 20:37
(Received via mailing list)
On 2/19/07, Jim B. <removed_email_address@domain.invalid> wrote:
> I'm sure the must be code for this already without me having to go
> through the array byte by byte.
>
> I have an array of bytes, I need to print this as a string?
>
> Note the array does not contain text.

Your question is ... confusing.

You have:

   a = [ 65, 32, 66 ]

When you print it, what do you want to see?

  "65, 32, 66" # use puts a.join(", ")
  "A B" # use puts a.map { |e| e.chr }.join
  "65 32 66" # use puts a.join(" ")
  "0x41, 0x20, 0x42" # use puts a.map { |e| "0x%02x" % e }.join

So, what are you looking for?

-austin
SonOfLilit (Guest)
on 2007-02-19 20:40
(Received via mailing list)
Strings are the ruby way to store arbitrary stuff in memory.

You don't necessarily need to access them as strings, they are just
general dynamically-allocated buffers of memory.

If you want something similar to C byte arrays, in ruby use strings.

e.g. for holding pixel data.

You don't need to PRINT it as a string, you just use String to store it.

That's why String has methods to get such values and turn them into
Ruby arrays, that is unpack (and pack, which does the opposite).


PLUG: http://rubymentor.rubyforge.org/wiki/wiki.pl RubyMentor is
looking for newbies to Ruby who could use our help
Jim B. (Guest)
on 2007-02-19 20:51
Thanks for your responses.

What I was doing was reading in some data from a binary file, this data
need to be printed in an xml document. I have now used
Base64.encode64(rawdata) and I am using this to write to the xml file.
It wasn't working at first, maybe because I opened the file in binary
mode.

Thanks,
Jim.
This topic is locked and can not be replied to.