Perl unpacks the "S *" equivalent in C

I am having trouble understanding Perl decompression in some code that I am reading, in particular with a template S*.

$data = "FF";
print "$data - ", unpack("S*", $data), "\n";
# > FF - 17990
  • What is equivalent to this in C?
  • Why?

Many thanks for your help

+4
source share
3 answers

Your code in C will look something like this:

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

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

Why? One of the main motives for packaging and unpacking was to simplify the exchange of binary data with C. structures.

perlpacktut is a good place to start.

+3
source

unpack 'S' uint16_t.

#include <stdint.h>
const char *data = "\x46\x41";
uint16_t n;
memcpy(&n, data, sizeof(n));  // n = 0x4146 or 0x4641

data, !


, .

little-endian (, x86, x64), unpack 'S'

uint16_t n = (data[1] << 8) | data[0];  // 0x4146

, unpack 'S'

uint16_t n = (data[0] << 8) | data[1];  // 0x4641

, , - :

uint16_t n = *((const uint16_t *)data);
+3

, , , .

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

"FF" .

: "FA" 16710?

-, "F" ASCII-70. 0100 0110 ( , , , ).

ASCII 'A-65. 0100 0001.

, F, 0100 0110 A, 0100 0001.

, , A:

0100 0001 0100 0110

0100 0001 0100 0110 16,710.

. , , , , , , .

+1

All Articles