String#unpack

J

Joe Van Dyk

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
 
M

Marcel Ward

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
 

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
474,216
Messages
2,571,120
Members
47,723
Latest member
Monika9748

Latest Threads

Top