in reply to How do I read a 24 bit integer?

Untested:
my $myinput = "\x00"; read FILE, $myinput, 3, 1; my $myinteger = unpack 'N', $myinput;
Basically, you're making a 32-bit integer by prefixing the 24-bit integer with 8 0-bits. Given a 32-bit integer, you can unpack it.

Replies are listed 'Best First'.
Re^2: How do I read a 24 bit integer?
by Anonymous Monk on Jan 01, 2010 at 15:42 UTC
    I think I understand that, but a couple of curves:

    1. How would I handle little endian data? Would it work correctly with no offset?

    2. The real data file (of course) is somewhat more complicated. It has several consecutive 24 bit integers. So how would I read and unpack say four at a time?

      1. Little endian would have 8 trailing 0 bits, wouldn't it? I'm sure you'll be able to add a NUL byte to a string.
      2. How about reading them into four variables, and prepending them with NUL bytes?
        Finally understanding this a bit, but it seems like I have one more problem.

        First, my code:

        read FILE, $myinput, 12; my($var1, $var2, $var3, $var4) = unpack('A3A3A3A3', $myinput); $var1 = unpack ('N', "\x00" . $var1); $var2 = unpack ('N', "\x00" . $var2); $var3 = unpack ('N', "\x00" . $var3); $var4 = unpack ('N', "\x00" . $var4); print "$var1\n"; print "$var2\n"; print "$var3\n"; print "$var4\n";
        The problem is that some of these values are legitimately zero, and when I try to print them, I get:
        Use of uninitialized value in concatenation (.) or string at myscript. +pl line 20.
        What did I miss to allow zeroes?