Perl Unpack & ldquo; S * & rdquo; Equivalent to C


I'm having a little trouble understanding Perl's unpack in some code I'm reading, specifically with the S* template.

$data = "FF";
print "$data - ", unpack("S*", $data), "\n";
# > FF - 17990

  1. What is the equivalent of this in C?
  2. Why?

Thanks very much for your help

Your code in C would look (roughly) like this:

const char *data = "FA";
unsigned short s;
memcpy( &s, data, strlen(data) );
printf("%s = %d\n", data, s);

This only handles your case with two characters, while unpack('S*',...) will return a list of shorts corresponding to its input.

Why? One of the primary motivations for pack and unpack was to make it easier interchange binary data with C structures.

perlpacktut is a good place to start.