On 10/12/06, Rolando Abarca <funkaster / gmail.com> wrote:
> Hi all,
> I'm parsing a binary file, and need to read an integer, something I
> would do in C like this:
>
> int b;
> read(f, &b, sizeof(int));
>
> obviously considering endianness. I'm pretty sure there has to be a
> faster way to do it, but this is how I'm doing it right now (as you
> can see, pretty naive):
>
> class IO
>   # read int, assume little endian
>   def geti
>     c1 = getc
>     c2 = getc
>     c3 = getc
>     c4 = getc
>     c4 << 3*8 | c3 << 2*8 | c2 << 8 | c1
>   end
> end
>
> What would be the ruby-way to do it?
> thanks for any tip...


class IO
  def geti( endian = :little )
    str = self.read( 4 )
    str = str.reverse if endian == :little
    str.unpack( 'N' )[0]
  end
end


The default for this method is to return the integer in little endian
byte order. You can change this by passing :big as an argument ...

io.geti :big

It does not have to be :big, but I'm just following the metaphor of
using :little for little endian byte order.

Blessings,
TwP