I have a small number < 10 and need to smash it into a unit16.

$count=17767; $c16 = pack("S", $count);

Congratulations, you did it on your first try.

printf("... c16=0x%04hx ...", ..., $c16, ...;

What makes you think printf's %x format wants to be given a string containing two bytes representing a packed value? %x wants a number. You know, like 15 or even '15'. %x doesn't magically decode whatever random packed format you throw at it and think "Hey! That might be a number packed in 'S' format. Why don't I interpret it that way in order to get a numeric value that I can then format into hexadecimal? I should!". What made you think it would?

You can just discard the rest of your hour of work.

Unpack?

Here you go:

$count = unpack("S", $c16);

- tye        


In reply to Re: Pack number to unsigned short (printf) by tye
in thread Pack number to unsigned short by BrianP

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.