[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

String#unpack

Joe Van Dyk

11/2/2006 1:03:00 AM

Hi,

I have a string that contains only a C int. Is the way to get it out:

the_string.unpack("i").first

? Is there another method that doesn't return an array?

Joe

1 Answer

Marcel Ward

11/2/2006 3:06:00 PM

0

On 02/11/06, Joe Van Dyk <joevandyk@gmail.com> wrote:
> Hi,
>
> I have a string that contains only a C int. Is the way to get it out:
>
> the_string.unpack("i").first
>

Looks ok to me. You should of course double check that both your
string data and Ruby's parsing share the same size and endian-ness on
all the platforms you will be working with. Also check out the 'i_'
option if you want to unpack according to the system's native byte
order.

> ? Is there another method that doesn't return an array?

I'm not sure. At least it should be one of the fastest ways because
it's coded in C - see pack.c.

The String#unpack method can extract multiple elements from a string
so it always returns an array cotaining the elements. For example, a
string containing 16 bytes of data representing 4 int values can be
extracted with:

"A\0\0\0B\0\0\0C\0\0\0D\0\0\0".unpack("iiii")
# => [65, 66, 67, 68]

So there is a good reason for it to be returning an array. You can
always write a wrapper for the single int operation if you want your
code to look cleaner.

class String
def unpack_first_int
unpack("i").first
end
end

"A\0\0\0B\0\0\0C\0\0\0D\0\0\0".unpack_first_int
# => 65

--
Marcel