in reply to Pack number to unsigned short

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        

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.