in reply to Re: Pack number to unsigned short (printf)
in thread Pack number to unsigned short

This node falls below the community's threshold of quality. You may see it by logging in.

Replies are listed 'Best First'.
Re^3: Pack number to unsigned short (formats)
by tye (Sage) on Aug 15, 2015 at 18:07 UTC
    Perl stores its ints at type j/J rather than binary.

    No, not really. Perl can store an integer value as an IV (signed integer of some size determined when Perl was built), a UV (unsigned), an NV (a double or similar), or a PV (a string). But that is at a lower layer that you normally don't have to worry about.

    Perl deals with scalars. A scalar can be a string or a number (and a few other types of values). Numeric values are automatically converted to string values when needed. String values are also automatically converted to numeric values but conversion in that direction can have issues, of course, as not all strings represent a numeric value.

    Perl's printf is not C's printf, though they certainly have a lot in common. For a numeric format specifier, Perl's printf() interprets the scalar as a numeric value. If the scalar already has a numeric value, than that is easy. If the scalar only has a string value, then Perl tries to interpret the string as a number, which means only interpreting it as a base-ten string (integer or floating-point).

    As noted in the first sentence of pack, the value returned is a string. That is appropriate as a Perl string can hold an arbitrary list of bytes.

    If you get a string with $str = pack "S", 0x3232;, then $str will be a string of two bytes where each byte has the value of 0x32. On an ASCII platform, that string is simply "22". If you then do printf "%x\n", $str, then Perl will output "16\n" because 0x16 == 22. You gave printf a scalar containing a string at the position where it needed a number (because '%x' expects a number) so it interpreted the string as a base-ten number and got the numeric value 22 from the string "22".

    And yet the number that you stored in that string was the number 0x3232.

    Maybe I can spend a few more hour and figure out how to UNPACK a binary blob into a string of 1s and 0s.

    That is easy: $base2 = unpack "B*", $blob;

    - tye        

Re^3: Pack number to unsigned short (printf)
by afoken (Chancellor) on Aug 15, 2015 at 08:55 UTC

    Did you notice the following text when you wrote your postings?

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

    Why do you constantly ignore it?

    Please edit your posts.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)