Not sure if this is more elegant than the OPed solution or than JavaFan's, but...

>perl -wMstrict -le "my $be24s = qq{\x01\x02\x03\x04\x05\x06\x07\x08\x09}; printf qq{%08lx }, $_ for unpack_be24($be24s); sub unpack_be24 { my ($s) = @_; return map unpack('N', qq{\x00$_}), unpack '(a3)*', $s; } " 00010203 00040506 00070809

Again, to make this little-endian, append the null byte and use  'V' for the unpack template.

Note: Of course, this doesn't actually read a 24-bit integer as requested in the OP, but I figure the reading part should be fairly straightforward.

Update: A slightly different approach, with one less map and an extra pack:

>perl -wMstrict -le "my $be24s = qq{\x11\x12\x13\x24\x25\x26\x37\x38\x39}; my $le24s = reverse $be24s; printf qq{%08lx }, $_ for unpack_be24($be24s); print ''; printf qq{%08lx }, $_ for unpack_le24($le24s); sub unpack_be24 { my ($s) = @_; return unpack 'N*', pack '(xa3)*', unpack '(a3)*', $s; } sub unpack_le24 { my ($s) = @_; return unpack 'V*', pack '(a3x)*', unpack '(a3)*', $s; } " 00111213 00242526 00373839 00373839 00242526 00111213

In reply to Re: How do I read a 24 bit integer? by AnomalousMonk
in thread How do I read a 24 bit integer? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.