# String.unpack endianess issue?

**URL:** <https://www.ruby-forum.com/t/string-unpack-endianess-issue/53134>\
**Category:** Ruby\
**Created:** [January 26, 2006, 7:23am UTC](https://www.ruby-forum.com/t/string-unpack-endianess-issue/53134 "2006-01-26T07:23:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![mansfiem](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/fbc32d/32.png) [@mansfiem](https://www.ruby-forum.com/u/mansfiem)\
**Post date:** [January 26, 2006, 7:23am UTC](https://www.ruby-forum.com/t/string-unpack-endianess-issue/53134/1 "2006-01-26T07:23:45Z")

</div>

In irb 0.9 (ruby 1.8.2) in cygwin/WindowsXP:

> a = [0, 0, 0, 6]  
> =\> [0, 0, 0, 6]  
> x = a.pack(“C\*”)  
> =\> “\000\000\000\006”  
> x.unpack(“I”)  
> =\> [100663296]  
> x.unpack(“V”)  
> =\> [100663296]

I would have though that at least one of “I” or “V” in the unpack call  
would have given me the correct answer, 6. I’m reading this data out  
of a binary file, stored in big-endian, but neither handles this.

I managed to get the right answer by doing:

x.unpack(“C\*”).reverse.pack(“C\*”).unpack(“I”)

But that seems rather silly. So I guess I’m asking:

1. Is unpack broken, or is there a big-endian option I missed?
2. Is there a more generic module/library for reading binary files?
3. Is there an existing modules/lib for reading MIDI files?

thanks…

---

<div class="post-metadata">

**Author:** ![mansfiem](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/fbc32d/32.png) [@mansfiem](https://www.ruby-forum.com/u/mansfiem)\
**Post date:** [January 26, 2006, 7:44am UTC](https://www.ruby-forum.com/t/string-unpack-endianess-issue/53134/2 "2006-01-26T07:44:51Z")

</div>

Matthew M. wrote:

> 1. Is unpack broken, or is there a big-endian option I missed?
> 2. Is there a more generic module/library for reading binary files?
> 3. Is there an existing modules/lib for reading MIDI files?
> 
> thanks…

irb(main):001:0\> a = [0, 0, 0, 6]  
=\> [0, 0, 0, 6]  
irb(main):002:0\> x = a.pack(“C\*”)  
=\> “\000\000\000\006”  
irb(main):003:0\> x.unpack “N”  
=\> [6]

For convenience, I wrote a set of object-oriented wrappers around  
pack/unpack. See bit-struct on raa.

---

<div class="post-metadata">

**Author:** ![mansfiem](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/fbc32d/32.png) [@mansfiem](https://www.ruby-forum.com/u/mansfiem)\
**Post date:** [January 26, 2006, 3:35pm UTC](https://www.ruby-forum.com/t/string-unpack-endianess-issue/53134/3 "2006-01-26T15:35:31Z")

</div>

> irb(main):001:0\> a = [0, 0, 0, 6]  
> =\> [0, 0, 0, 6]  
> irb(main):002:0\> x = a.pack(“C\*”)  
> =\> “\000\000\000\006”  
> irb(main):003:0\> x.unpack “N”  
> =\> [6]
> 
> For convenience, I wrote a set of object-oriented wrappers around  
> pack/unpack. See bit-struct on raa.

Ah, thanks. I noticed the “V” as I searched for “endian” in the docs,  
but I missed the “N”. Should have searched on “byte order”. Thanks…
