# String#unpack

**URL:** <https://www.ruby-forum.com/t/string-unpack/74714>\
**Category:** Ruby\
**Created:** [November 7, 2006, 10:53am UTC](https://www.ruby-forum.com/t/string-unpack/74714 "2006-11-07T10:53:39Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [November 7, 2006, 10:53am UTC](https://www.ruby-forum.com/t/string-unpack/74714/1 "2006-11-07T10:53:39Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![joe-dumoulin](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/9dc877/32.png) [@joe-dumoulin](https://www.ruby-forum.com/u/joe-dumoulin)\
**Post date:** [November 7, 2006, 10:54am UTC](https://www.ruby-forum.com/t/string-unpack/74714/2 "2006-11-07T10:54:56Z")

</div>

On 02/11/06, Joe Van D. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) 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
