byte array to string

J

Jim Bob

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
 
A

Austin Ziegler

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
 
S

SonOfLilit

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
 
J

Jim Bob

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top