# unpack("N\*")

**URL:** <https://www.ruby-forum.com/t/unpack-n/171834>\
**Category:** Ruby\
**Created:** [July 9, 2009, 10:18pm UTC](https://www.ruby-forum.com/t/unpack-n/171834 "2009-07-09T22:18:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![z4n9ief](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/7993a0/32.png) [@z4n9ief](https://www.ruby-forum.com/u/z4n9ief)\
**Post date:** [July 9, 2009, 10:18pm UTC](https://www.ruby-forum.com/t/unpack-n/171834/1 "2009-07-09T22:18:22Z")

</div>

Hi,

I’m trying to unpack a string into network byte order (big-endian), such  
as the following method:

# Convert an 8-bit or 16-bit string to an array of big-endian words

# In 8-bit function, characters \>255 have their hi-byte silently

ignored.  
def str2binb(str)  
bin = []  
mask = (1 \<\< 8) - 1  
i = 0  
while (i \< str.length \* 8)  
bin[i\>\>5] ||= 0  
bin[i\>\>5] |= (str[i / 8] & mask) \<\< (32 - 8 - i%32)  
i += 8  
end  
bin  
end

But after using unpack(“N\*”) method (according to  
[http://www.ruby-doc.org/core/classes/String.html#M000760](http://www.ruby-doc.org/core/classes/String.html#M000760)), the result is  
not exactly the same. For instance:

> > str2binb(“Abcdefghijklmnopqrstuvwxyz”)  
> > =\> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,  
> > 1970698104, 2038038528]  
> > “Abcdefghijklmnopqrstuvwxyz”.unpack(“N\*”)  
> > =\> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,  
> > 1970698104]

Moreover, if I try “a”.unpack(“N\*”), Ruby returns a void array…

Thanks for any suggestions.

---

<div class="post-metadata">

**Author:** ![z4n9ief](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/7993a0/32.png) [@z4n9ief](https://www.ruby-forum.com/u/z4n9ief)\
**Post date:** [July 9, 2009, 10:34pm UTC](https://www.ruby-forum.com/t/unpack-n/171834/2 "2009-07-09T22:34:05Z")

</div>

Zangief I. wrote:

> mask = (1 \<\< 8) - 1  
> [class String - RDoc Documentation](http://www.ruby-doc.org/core/classes/String.html#M000760)), the result is  
> not exactly the same. For instance:
> 
> > > str2binb(“Abcdefghijklmnopqrstuvwxyz”)  
> > > =\> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,  
> > > 1970698104, 2038038528]  
> > > “Abcdefghijklmnopqrstuvwxyz”.unpack(“N\*”)  
> > > =\> [1096967012, 1701209960, 1768581996, 1835954032, 1903326068,  
> > > 1970698104]
> 
> Moreover, if I try “a”.unpack(“N\*”), Ruby returns a void array…

Better pad with null chars (\0) up to a multiple of 4 bytes if you want  
the same behavior. I guess unpack(“N\*”) stops if there is not a full 4  
chars.

---

<div class="post-metadata">

**Author:** ![z4n9ief](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/z/7993a0/32.png) [@z4n9ief](https://www.ruby-forum.com/u/z4n9ief)\
**Post date:** [July 10, 2009, 1:05pm UTC](https://www.ruby-forum.com/t/unpack-n/171834/3 "2009-07-10T13:05:44Z")

</div>

Many thanks! 🙂
