Commit | Line | Data |
---|---|---|
34babc16 JH |
1 | =head1 NAME |
2 | ||
3 | perlpacktut - tutorial on C<pack> and C<unpack> | |
4 | ||
5 | =head1 DESCRIPTION | |
6 | ||
7 | C<pack> and C<unpack> are two functions for transforming data according | |
8 | to a user-defined template, between the guarded way Perl stores values | |
47b6252e | 9 | and some well-defined representation as might be required in the |
34babc16 JH |
10 | environment of a Perl program. Unfortunately, they're also two of |
11 | the most misunderstood and most often overlooked functions that Perl | |
12 | provides. This tutorial will demystify them for you. | |
13 | ||
14 | ||
15 | =head1 The Basic Principle | |
16 | ||
17 | Most programming languages don't shelter the memory where variables are | |
18 | stored. In C, for instance, you can take the address of some variable, | |
19 | and the C<sizeof> operator tells you how many bytes are allocated to | |
20 | the variable. Using the address and the size, you may access the storage | |
21 | to your heart's content. | |
22 | ||
23 | In Perl, you just can't access memory at random, but the structural and | |
24 | representational conversion provided by C<pack> and C<unpack> is an | |
25 | excellent alternative. The C<pack> function converts values to a byte | |
26 | sequence containing representations according to a given specification, | |
27 | the so-called "template" argument. C<unpack> is the reverse process, | |
28 | deriving some values from the contents of a string of bytes. (Be cautioned, | |
29 | however, that not all that has been packed together can be neatly unpacked - | |
30 | a very common experience as seasoned travellers are likely to confirm.) | |
31 | ||
32 | Why, you may ask, would you need a chunk of memory containing some values | |
33 | in binary representation? One good reason is input and output accessing | |
34 | some file, a device, or a network connection, whereby this binary | |
35 | representation is either forced on you or will give you some benefit | |
36 | in processing. Another cause is passing data to some system call that | |
37 | is not available as a Perl function: C<syscall> requires you to provide | |
38 | parameters stored in the way it happens in a C program. Even text processing | |
39 | (as shown in the next section) may be simplified with judicious usage | |
40 | of these two functions. | |
41 | ||
42 | To see how (un)packing works, we'll start with a simple template | |
43 | code where the conversion is in low gear: between the contents of a byte | |
44 | sequence and a string of hexadecimal digits. Let's use C<unpack>, since | |
47b6252e | 45 | this is likely to remind you of a dump program, or some desperate last |
34babc16 JH |
46 | message unfortunate programs are wont to throw at you before they expire |
47 | into the wild blue yonder. Assuming that the variable C<$mem> holds a | |
48 | sequence of bytes that we'd like to inspect without assuming anything | |
49 | about its meaning, we can write | |
50 | ||
51 | my( $hex ) = unpack( 'H*', $mem ); | |
52 | print "$hex\n"; | |
53 | ||
54 | whereupon we might see something like this, with each pair of hex digits | |
55 | corresponding to a byte: | |
56 | ||
57 | 41204d414e204120504c414e20412043414e414c2050414e414d41 | |
58 | ||
47b6252e | 59 | What was in this chunk of memory? Numbers, characters, or a mixture of |
34babc16 JH |
60 | both? Assuming that we're on a computer where ASCII (or some similar) |
61 | encoding is used: hexadecimal values in the range C<0x40> - C<0x5A> | |
47f22e19 | 62 | indicate an uppercase letter, and C<0x20> encodes a space. So we might |
34babc16 JH |
63 | assume it is a piece of text, which some are able to read like a tabloid; |
64 | but others will have to get hold of an ASCII table and relive that | |
65 | firstgrader feeling. Not caring too much about which way to read this, | |
66 | we note that C<unpack> with the template code C<H> converts the contents | |
67 | of a sequence of bytes into the customary hexadecimal notation. Since | |
68 | "a sequence of" is a pretty vague indication of quantity, C<H> has been | |
69 | defined to convert just a single hexadecimal digit unless it is followed | |
70 | by a repeat count. An asterisk for the repeat count means to use whatever | |
71 | remains. | |
72 | ||
73 | The inverse operation - packing byte contents from a string of hexadecimal | |
74 | digits - is just as easily written. For instance: | |
75 | ||
4e848ca9 | 76 | my $s = pack( 'H2' x 10, 30..39 ); |
34babc16 JH |
77 | print "$s\n"; |
78 | ||
79 | Since we feed a list of ten 2-digit hexadecimal strings to C<pack>, the | |
80 | pack template should contain ten pack codes. If this is run on a computer | |
81 | with ASCII character coding, it will print C<0123456789>. | |
82 | ||
34babc16 JH |
83 | =head1 Packing Text |
84 | ||
85 | Let's suppose you've got to read in a data file like this: | |
86 | ||
87 | Date |Description | Income|Expenditure | |
88 | 01/24/2001 Ahmed's Camel Emporium 1147.99 | |
89 | 01/28/2001 Flea spray 24.99 | |
90 | 01/29/2001 Camel rides to tourists 235.00 | |
91 | ||
92 | How do we do it? You might think first to use C<split>; however, since | |
93 | C<split> collapses blank fields, you'll never know whether a record was | |
94 | income or expenditure. Oops. Well, you could always use C<substr>: | |
95 | ||
96 | while (<>) { | |
97 | my $date = substr($_, 0, 11); | |
98 | my $desc = substr($_, 12, 27); | |
99 | my $income = substr($_, 40, 7); | |
100 | my $expend = substr($_, 52, 7); | |
101 | ... | |
102 | } | |
103 | ||
104 | It's not really a barrel of laughs, is it? In fact, it's worse than it | |
105 | may seem; the eagle-eyed may notice that the first field should only be | |
106 | 10 characters wide, and the error has propagated right through the other | |
107 | numbers - which we've had to count by hand. So it's error-prone as well | |
108 | as horribly unfriendly. | |
109 | ||
110 | Or maybe we could use regular expressions: | |
7207e29d | 111 | |
34babc16 JH |
112 | while (<>) { |
113 | my($date, $desc, $income, $expend) = | |
114 | m|(\d\d/\d\d/\d{4}) (.{27}) (.{7})(.*)|; | |
115 | ... | |
116 | } | |
117 | ||
118 | Urgh. Well, it's a bit better, but - well, would you want to maintain | |
119 | that? | |
120 | ||
121 | Hey, isn't Perl supposed to make this sort of thing easy? Well, it does, | |
122 | if you use the right tools. C<pack> and C<unpack> are designed to help | |
123 | you out when dealing with fixed-width data like the above. Let's have a | |
124 | look at a solution with C<unpack>: | |
125 | ||
126 | while (<>) { | |
127 | my($date, $desc, $income, $expend) = unpack("A10xA27xA7A*", $_); | |
128 | ... | |
129 | } | |
130 | ||
131 | That looks a bit nicer; but we've got to take apart that weird template. | |
132 | Where did I pull that out of? | |
133 | ||
134 | OK, let's have a look at some of our data again; in fact, we'll include | |
135 | the headers, and a handy ruler so we can keep track of where we are. | |
136 | ||
137 | 1 2 3 4 5 | |
138 | 1234567890123456789012345678901234567890123456789012345678 | |
139 | Date |Description | Income|Expenditure | |
140 | 01/28/2001 Flea spray 24.99 | |
141 | 01/29/2001 Camel rides to tourists 235.00 | |
142 | ||
47b6252e | 143 | From this, we can see that the date column stretches from column 1 to |
34babc16 JH |
144 | column 10 - ten characters wide. The C<pack>-ese for "character" is |
145 | C<A>, and ten of them are C<A10>. So if we just wanted to extract the | |
146 | dates, we could say this: | |
147 | ||
148 | my($date) = unpack("A10", $_); | |
149 | ||
150 | OK, what's next? Between the date and the description is a blank column; | |
151 | we want to skip over that. The C<x> template means "skip forward", so we | |
152 | want one of those. Next, we have another batch of characters, from 12 to | |
153 | 38. That's 27 more characters, hence C<A27>. (Don't make the fencepost | |
154 | error - there are 27 characters between 12 and 38, not 26. Count 'em!) | |
155 | ||
156 | Now we skip another character and pick up the next 7 characters: | |
157 | ||
158 | my($date,$description,$income) = unpack("A10xA27xA7", $_); | |
159 | ||
160 | Now comes the clever bit. Lines in our ledger which are just income and | |
161 | not expenditure might end at column 46. Hence, we don't want to tell our | |
162 | C<unpack> pattern that we B<need> to find another 12 characters; we'll | |
163 | just say "if there's anything left, take it". As you might guess from | |
164 | regular expressions, that's what the C<*> means: "use everything | |
165 | remaining". | |
166 | ||
167 | =over 3 | |
168 | ||
169 | =item * | |
170 | ||
171 | Be warned, though, that unlike regular expressions, if the C<unpack> | |
172 | template doesn't match the incoming data, Perl will scream and die. | |
173 | ||
174 | =back | |
175 | ||
176 | ||
177 | Hence, putting it all together: | |
178 | ||
49704364 | 179 | my($date,$description,$income,$expend) = unpack("A10xA27xA7xA*", $_); |
34babc16 JH |
180 | |
181 | Now, that's our data parsed. I suppose what we might want to do now is | |
182 | total up our income and expenditure, and add another line to the end of | |
183 | our ledger - in the same format - saying how much we've brought in and | |
184 | how much we've spent: | |
185 | ||
186 | while (<>) { | |
187 | my($date, $desc, $income, $expend) = unpack("A10xA27xA7xA*", $_); | |
188 | $tot_income += $income; | |
189 | $tot_expend += $expend; | |
190 | } | |
191 | ||
192 | $tot_income = sprintf("%.2f", $tot_income); # Get them into | |
193 | $tot_expend = sprintf("%.2f", $tot_expend); # "financial" format | |
194 | ||
195 | $date = POSIX::strftime("%m/%d/%Y", localtime); | |
196 | ||
197 | # OK, let's go: | |
198 | ||
199 | print pack("A10xA27xA7xA*", $date, "Totals", $tot_income, $tot_expend); | |
200 | ||
201 | Oh, hmm. That didn't quite work. Let's see what happened: | |
202 | ||
203 | 01/24/2001 Ahmed's Camel Emporium 1147.99 | |
204 | 01/28/2001 Flea spray 24.99 | |
205 | 01/29/2001 Camel rides to tourists 1235.00 | |
206 | 03/23/2001Totals 1235.001172.98 | |
207 | ||
208 | OK, it's a start, but what happened to the spaces? We put C<x>, didn't | |
209 | we? Shouldn't it skip forward? Let's look at what L<perlfunc/pack> says: | |
210 | ||
211 | x A null byte. | |
212 | ||
213 | Urgh. No wonder. There's a big difference between "a null byte", | |
214 | character zero, and "a space", character 32. Perl's put something | |
215 | between the date and the description - but unfortunately, we can't see | |
216 | it! | |
217 | ||
218 | What we actually need to do is expand the width of the fields. The C<A> | |
219 | format pads any non-existent characters with spaces, so we can use the | |
220 | additional spaces to line up our fields, like this: | |
221 | ||
222 | print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend); | |
223 | ||
224 | (Note that you can put spaces in the template to make it more readable, | |
225 | but they don't translate to spaces in the output.) Here's what we got | |
226 | this time: | |
227 | ||
228 | 01/24/2001 Ahmed's Camel Emporium 1147.99 | |
229 | 01/28/2001 Flea spray 24.99 | |
230 | 01/29/2001 Camel rides to tourists 1235.00 | |
231 | 03/23/2001 Totals 1235.00 1172.98 | |
232 | ||
233 | That's a bit better, but we still have that last column which needs to | |
234 | be moved further over. There's an easy way to fix this up: | |
235 | unfortunately, we can't get C<pack> to right-justify our fields, but we | |
236 | can get C<sprintf> to do it: | |
237 | ||
238 | $tot_income = sprintf("%.2f", $tot_income); | |
239 | $tot_expend = sprintf("%12.2f", $tot_expend); | |
240 | $date = POSIX::strftime("%m/%d/%Y", localtime); | |
241 | print pack("A11 A28 A8 A*", $date, "Totals", $tot_income, $tot_expend); | |
242 | ||
243 | This time we get the right answer: | |
244 | ||
245 | 01/28/2001 Flea spray 24.99 | |
246 | 01/29/2001 Camel rides to tourists 1235.00 | |
247 | 03/23/2001 Totals 1235.00 1172.98 | |
248 | ||
249 | So that's how we consume and produce fixed-width data. Let's recap what | |
250 | we've seen of C<pack> and C<unpack> so far: | |
251 | ||
252 | =over 3 | |
253 | ||
254 | =item * | |
255 | ||
256 | Use C<pack> to go from several pieces of data to one fixed-width | |
257 | version; use C<unpack> to turn a fixed-width-format string into several | |
258 | pieces of data. | |
259 | ||
260 | =item * | |
261 | ||
262 | The pack format C<A> means "any character"; if you're C<pack>ing and | |
263 | you've run out of things to pack, C<pack> will fill the rest up with | |
264 | spaces. | |
265 | ||
266 | =item * | |
267 | ||
268 | C<x> means "skip a byte" when C<unpack>ing; when C<pack>ing, it means | |
269 | "introduce a null byte" - that's probably not what you mean if you're | |
270 | dealing with plain text. | |
271 | ||
272 | =item * | |
273 | ||
274 | You can follow the formats with numbers to say how many characters | |
275 | should be affected by that format: C<A12> means "take 12 characters"; | |
276 | C<x6> means "skip 6 bytes" or "character 0, 6 times". | |
277 | ||
278 | =item * | |
279 | ||
280 | Instead of a number, you can use C<*> to mean "consume everything else | |
281 | left". | |
282 | ||
283 | B<Warning>: when packing multiple pieces of data, C<*> only means | |
284 | "consume all of the current piece of data". That's to say | |
285 | ||
286 | pack("A*A*", $one, $two) | |
287 | ||
288 | packs all of C<$one> into the first C<A*> and then all of C<$two> into | |
289 | the second. This is a general principle: each format character | |
290 | corresponds to one piece of data to be C<pack>ed. | |
291 | ||
292 | =back | |
293 | ||
294 | ||
295 | ||
296 | =head1 Packing Numbers | |
297 | ||
298 | So much for textual data. Let's get onto the meaty stuff that C<pack> | |
299 | and C<unpack> are best at: handling binary formats for numbers. There is, | |
300 | of course, not just one binary format - life would be too simple - but | |
301 | Perl will do all the finicky labor for you. | |
302 | ||
303 | ||
304 | =head2 Integers | |
305 | ||
306 | Packing and unpacking numbers implies conversion to and from some | |
307 | I<specific> binary representation. Leaving floating point numbers | |
308 | aside for the moment, the salient properties of any such representation | |
309 | are: | |
310 | ||
311 | =over 4 | |
312 | ||
313 | =item * | |
314 | ||
315 | the number of bytes used for storing the integer, | |
316 | ||
317 | =item * | |
318 | ||
319 | whether the contents are interpreted as a signed or unsigned number, | |
320 | ||
321 | =item * | |
322 | ||
323 | the byte ordering: whether the first byte is the least or most | |
324 | significant byte (or: little-endian or big-endian, respectively). | |
325 | ||
326 | =back | |
327 | ||
328 | So, for instance, to pack 20302 to a signed 16 bit integer in your | |
329 | computer's representation you write | |
330 | ||
331 | my $ps = pack( 's', 20302 ); | |
332 | ||
333 | Again, the result is a string, now containing 2 bytes. If you print | |
334 | this string (which is, generally, not recommended) you might see | |
335 | C<ON> or C<NO> (depending on your system's byte ordering) - or something | |
336 | entirely different if your computer doesn't use ASCII character encoding. | |
337 | Unpacking C<$ps> with the same template returns the original integer value: | |
338 | ||
339 | my( $s ) = unpack( 's', $ps ); | |
340 | ||
341 | This is true for all numeric template codes. But don't expect miracles: | |
47b6252e | 342 | if the packed value exceeds the allotted byte capacity, high order bits |
34babc16 JH |
343 | are silently discarded, and unpack certainly won't be able to pull them |
344 | back out of some magic hat. And, when you pack using a signed template | |
345 | code such as C<s>, an excess value may result in the sign bit | |
346 | getting set, and unpacking this will smartly return a negative value. | |
347 | ||
348 | 16 bits won't get you too far with integers, but there is C<l> and C<L> | |
349 | for signed and unsigned 32-bit integers. And if this is not enough and | |
350 | your system supports 64 bit integers you can push the limits much closer | |
351 | to infinity with pack codes C<q> and C<Q>. A notable exception is provided | |
352 | by pack codes C<i> and C<I> for signed and unsigned integers of the | |
353 | "local custom" variety: Such an integer will take up as many bytes as | |
354 | a local C compiler returns for C<sizeof(int)>, but it'll use I<at least> | |
355 | 32 bits. | |
356 | ||
357 | Each of the integer pack codes C<sSlLqQ> results in a fixed number of bytes, | |
358 | no matter where you execute your program. This may be useful for some | |
359 | applications, but it does not provide for a portable way to pass data | |
360 | structures between Perl and C programs (bound to happen when you call | |
361 | XS extensions or the Perl function C<syscall>), or when you read or | |
362 | write binary files. What you'll need in this case are template codes that | |
363 | depend on what your local C compiler compiles when you code C<short> or | |
364 | C<unsigned long>, for instance. These codes and their corresponding | |
365 | byte lengths are shown in the table below. Since the C standard leaves | |
366 | much leeway with respect to the relative sizes of these data types, actual | |
367 | values may vary, and that's why the values are given as expressions in | |
368 | C and Perl. (If you'd like to use values from C<%Config> in your program | |
369 | you have to import it with C<use Config>.) | |
370 | ||
371 | signed unsigned byte length in C byte length in Perl | |
f8b4d74f WL |
372 | s! S! sizeof(short) $Config{shortsize} |
373 | i! I! sizeof(int) $Config{intsize} | |
374 | l! L! sizeof(long) $Config{longsize} | |
d832b8f6 | 375 | q! Q! sizeof(long long) $Config{longlongsize} |
34babc16 JH |
376 | |
377 | The C<i!> and C<I!> codes aren't different from C<i> and C<I>; they are | |
378 | tolerated for completeness' sake. | |
379 | ||
380 | ||
381 | =head2 Unpacking a Stack Frame | |
382 | ||
383 | Requesting a particular byte ordering may be necessary when you work with | |
47f22e19 | 384 | binary data coming from some specific architecture whereas your program could |
34babc16 JH |
385 | run on a totally different system. As an example, assume you have 24 bytes |
386 | containing a stack frame as it happens on an Intel 8086: | |
387 | ||
388 | +---------+ +----+----+ +---------+ | |
389 | TOS: | IP | TOS+4:| FL | FH | FLAGS TOS+14:| SI | | |
390 | +---------+ +----+----+ +---------+ | |
391 | | CS | | AL | AH | AX | DI | | |
392 | +---------+ +----+----+ +---------+ | |
393 | | BL | BH | BX | BP | | |
394 | +----+----+ +---------+ | |
395 | | CL | CH | CX | DS | | |
396 | +----+----+ +---------+ | |
397 | | DL | DH | DX | ES | | |
398 | +----+----+ +---------+ | |
399 | ||
400 | First, we note that this time-honored 16-bit CPU uses little-endian order, | |
401 | and that's why the low order byte is stored at the lower address. To | |
9dc383df | 402 | unpack such a (unsigned) short we'll have to use code C<v>. A repeat |
34babc16 JH |
403 | count unpacks all 12 shorts: |
404 | ||
405 | my( $ip, $cs, $flags, $ax, $bx, $cd, $dx, $si, $di, $bp, $ds, $es ) = | |
406 | unpack( 'v12', $frame ); | |
407 | ||
408 | Alternatively, we could have used C<C> to unpack the individually | |
409 | accessible byte registers FL, FH, AL, AH, etc.: | |
410 | ||
411 | my( $fl, $fh, $al, $ah, $bl, $bh, $cl, $ch, $dl, $dh ) = | |
412 | unpack( 'C10', substr( $frame, 4, 10 ) ); | |
413 | ||
414 | It would be nice if we could do this in one fell swoop: unpack a short, | |
415 | back up a little, and then unpack 2 bytes. Since Perl I<is> nice, it | |
416 | proffers the template code C<X> to back up one byte. Putting this all | |
417 | together, we may now write: | |
418 | ||
419 | my( $ip, $cs, | |
420 | $flags,$fl,$fh, | |
421 | $ax,$al,$ah, $bx,$bl,$bh, $cx,$cl,$ch, $dx,$dl,$dh, | |
422 | $si, $di, $bp, $ds, $es ) = | |
423 | unpack( 'v2' . ('vXXCC' x 5) . 'v5', $frame ); | |
424 | ||
49704364 WL |
425 | (The clumsy construction of the template can be avoided - just read on!) |
426 | ||
47f22e19 | 427 | We've taken some pains to construct the template so that it matches |
34babc16 JH |
428 | the contents of our frame buffer. Otherwise we'd either get undefined values, |
429 | or C<unpack> could not unpack all. If C<pack> runs out of items, it will | |
47f22e19 WL |
430 | supply null strings (which are coerced into zeroes whenever the pack code |
431 | says so). | |
34babc16 JH |
432 | |
433 | ||
434 | =head2 How to Eat an Egg on a Net | |
435 | ||
436 | The pack code for big-endian (high order byte at the lowest address) is | |
437 | C<n> for 16 bit and C<N> for 32 bit integers. You use these codes | |
438 | if you know that your data comes from a compliant architecture, but, | |
439 | surprisingly enough, you should also use these pack codes if you | |
440 | exchange binary data, across the network, with some system that you | |
441 | know next to nothing about. The simple reason is that this | |
442 | order has been chosen as the I<network order>, and all standard-fearing | |
443 | programs ought to follow this convention. (This is, of course, a stern | |
444 | backing for one of the Lilliputian parties and may well influence the | |
445 | political development there.) So, if the protocol expects you to send | |
446 | a message by sending the length first, followed by just so many bytes, | |
447 | you could write: | |
448 | ||
449 | my $buf = pack( 'N', length( $msg ) ) . $msg; | |
450 | ||
451 | or even: | |
452 | ||
453 | my $buf = pack( 'NA*', length( $msg ), $msg ); | |
454 | ||
455 | and pass C<$buf> to your send routine. Some protocols demand that the | |
456 | count should include the length of the count itself: then just add 4 | |
457 | to the data length. (But make sure to read L<"Lengths and Widths"> before | |
458 | you really code this!) | |
459 | ||
460 | ||
59f20ca5 MHM |
461 | =head2 Byte-order modifiers |
462 | ||
463 | In the previous sections we've learned how to use C<n>, C<N>, C<v> and | |
464 | C<V> to pack and unpack integers with big- or little-endian byte-order. | |
465 | While this is nice, it's still rather limited because it leaves out all | |
466 | kinds of signed integers as well as 64-bit integers. For example, if you | |
467 | wanted to unpack a sequence of signed big-endian 16-bit integers in a | |
468 | platform-independent way, you would have to write: | |
469 | ||
470 | my @data = unpack 's*', pack 'S*', unpack 'n*', $buf; | |
471 | ||
c4ecfaf1 | 472 | This is ugly. As of Perl 5.9.2, there's a much nicer way to express your |
59f20ca5 MHM |
473 | desire for a certain byte-order: the C<E<gt>> and C<E<lt>> modifiers. |
474 | C<E<gt>> is the big-endian modifier, while C<E<lt>> is the little-endian | |
475 | modifier. Using them, we could rewrite the above code as: | |
476 | ||
477 | my @data = unpack 's>*', $buf; | |
478 | ||
479 | As you can see, the "big end" of the arrow touches the C<s>, which is a | |
480 | nice way to remember that C<E<gt>> is the big-endian modifier. The same | |
481 | obviously works for C<E<lt>>, where the "little end" touches the code. | |
482 | ||
483 | You will probably find these modifiers even more useful if you have | |
484 | to deal with big- or little-endian C structures. Be sure to read | |
485 | L<"Packing and Unpacking C Structures"> for more on that. | |
486 | ||
34babc16 JH |
487 | |
488 | =head2 Floating point Numbers | |
489 | ||
490 | For packing floating point numbers you have the choice between the | |
59f20ca5 MHM |
491 | pack codes C<f>, C<d>, C<F> and C<D>. C<f> and C<d> pack into (or unpack |
492 | from) single-precision or double-precision representation as it is provided | |
493 | by your system. If your systems supports it, C<D> can be used to pack and | |
494 | unpack extended-precision floating point values (C<long double>), which | |
495 | can offer even more resolution than C<f> or C<d>. C<F> packs an C<NV>, | |
496 | which is the floating point type used by Perl internally. (There | |
34babc16 JH |
497 | is no such thing as a network representation for reals, so if you want |
498 | to send your real numbers across computer boundaries, you'd better stick | |
499 | to ASCII representation, unless you're absolutely sure what's on the other | |
59f20ca5 MHM |
500 | end of the line. For the even more adventuresome, you can use the byte-order |
501 | modifiers from the previous section also on floating point codes.) | |
34babc16 JH |
502 | |
503 | ||
504 | ||
505 | =head1 Exotic Templates | |
506 | ||
507 | ||
508 | =head2 Bit Strings | |
509 | ||
510 | Bits are the atoms in the memory world. Access to individual bits may | |
511 | have to be used either as a last resort or because it is the most | |
512 | convenient way to handle your data. Bit string (un)packing converts | |
513 | between strings containing a series of C<0> and C<1> characters and | |
514 | a sequence of bytes each containing a group of 8 bits. This is almost | |
515 | as simple as it sounds, except that there are two ways the contents of | |
516 | a byte may be written as a bit string. Let's have a look at an annotated | |
517 | byte: | |
518 | ||
519 | 7 6 5 4 3 2 1 0 | |
520 | +-----------------+ | |
521 | | 1 0 0 0 1 1 0 0 | | |
522 | +-----------------+ | |
523 | MSB LSB | |
524 | ||
525 | It's egg-eating all over again: Some think that as a bit string this should | |
526 | be written "10001100" i.e. beginning with the most significant bit, others | |
527 | insist on "00110001". Well, Perl isn't biased, so that's why we have two bit | |
528 | string codes: | |
529 | ||
530 | $byte = pack( 'B8', '10001100' ); # start with MSB | |
531 | $byte = pack( 'b8', '00110001' ); # start with LSB | |
532 | ||
533 | It is not possible to pack or unpack bit fields - just integral bytes. | |
534 | C<pack> always starts at the next byte boundary and "rounds up" to the | |
535 | next multiple of 8 by adding zero bits as required. (If you do want bit | |
536 | fields, there is L<perlfunc/vec>. Or you could implement bit field | |
537 | handling at the character string level, using split, substr, and | |
538 | concatenation on unpacked bit strings.) | |
539 | ||
540 | To illustrate unpacking for bit strings, we'll decompose a simple | |
541 | status register (a "-" stands for a "reserved" bit): | |
542 | ||
543 | +-----------------+-----------------+ | |
544 | | S Z - A - P - C | - - - - O D I T | | |
545 | +-----------------+-----------------+ | |
546 | MSB LSB MSB LSB | |
547 | ||
548 | Converting these two bytes to a string can be done with the unpack | |
549 | template C<'b16'>. To obtain the individual bit values from the bit | |
47f22e19 | 550 | string we use C<split> with the "empty" separator pattern which dissects |
34babc16 JH |
551 | into individual characters. Bit values from the "reserved" positions are |
552 | simply assigned to C<undef>, a convenient notation for "I don't care where | |
553 | this goes". | |
554 | ||
49704364 | 555 | ($carry, undef, $parity, undef, $auxcarry, undef, $zero, $sign, |
34babc16 | 556 | $trace, $interrupt, $direction, $overflow) = |
47f22e19 | 557 | split( //, unpack( 'b16', $status ) ); |
34babc16 JH |
558 | |
559 | We could have used an unpack template C<'b12'> just as well, since the | |
560 | last 4 bits can be ignored anyway. | |
561 | ||
562 | ||
563 | =head2 Uuencoding | |
564 | ||
565 | Another odd-man-out in the template alphabet is C<u>, which packs an | |
566 | "uuencoded string". ("uu" is short for Unix-to-Unix.) Chances are that | |
567 | you won't ever need this encoding technique which was invented to overcome | |
568 | the shortcomings of old-fashioned transmission mediums that do not support | |
569 | other than simple ASCII data. The essential recipe is simple: Take three | |
570 | bytes, or 24 bits. Split them into 4 six-packs, adding a space (0x20) to | |
571 | each. Repeat until all of the data is blended. Fold groups of 4 bytes into | |
572 | lines no longer than 60 and garnish them in front with the original byte count | |
573 | (incremented by 0x20) and a C<"\n"> at the end. - The C<pack> chef will | |
574 | prepare this for you, a la minute, when you select pack code C<u> on the menu: | |
575 | ||
576 | my $uubuf = pack( 'u', $bindat ); | |
577 | ||
578 | A repeat count after C<u> sets the number of bytes to put into an | |
579 | uuencoded line, which is the maximum of 45 by default, but could be | |
580 | set to some (smaller) integer multiple of three. C<unpack> simply ignores | |
581 | the repeat count. | |
582 | ||
583 | ||
584 | =head2 Doing Sums | |
585 | ||
586 | An even stranger template code is C<%>E<lt>I<number>E<gt>. First, because | |
587 | it's used as a prefix to some other template code. Second, because it | |
588 | cannot be used in C<pack> at all, and third, in C<unpack>, doesn't return the | |
589 | data as defined by the template code it precedes. Instead it'll give you an | |
590 | integer of I<number> bits that is computed from the data value by | |
591 | doing sums. For numeric unpack codes, no big feat is achieved: | |
592 | ||
593 | my $buf = pack( 'iii', 100, 20, 3 ); | |
594 | print unpack( '%32i3', $buf ), "\n"; # prints 123 | |
595 | ||
596 | For string values, C<%> returns the sum of the byte values saving | |
597 | you the trouble of a sum loop with C<substr> and C<ord>: | |
598 | ||
599 | print unpack( '%32A*', "\x01\x10" ), "\n"; # prints 17 | |
600 | ||
601 | Although the C<%> code is documented as returning a "checksum": | |
602 | don't put your trust in such values! Even when applied to a small number | |
603 | of bytes, they won't guarantee a noticeable Hamming distance. | |
604 | ||
605 | In connection with C<b> or C<B>, C<%> simply adds bits, and this can be put | |
606 | to good use to count set bits efficiently: | |
607 | ||
608 | my $bitcount = unpack( '%32b*', $mask ); | |
609 | ||
610 | And an even parity bit can be determined like this: | |
611 | ||
612 | my $evenparity = unpack( '%1b*', $mask ); | |
613 | ||
614 | ||
615 | =head2 Unicode | |
616 | ||
617 | Unicode is a character set that can represent most characters in most of | |
618 | the world's languages, providing room for over one million different | |
619 | characters. Unicode 3.1 specifies 94,140 characters: The Basic Latin | |
620 | characters are assigned to the numbers 0 - 127. The Latin-1 Supplement with | |
621 | characters that are used in several European languages is in the next | |
622 | range, up to 255. After some more Latin extensions we find the character | |
47b6252e | 623 | sets from languages using non-Roman alphabets, interspersed with a |
34babc16 | 624 | variety of symbol sets such as currency symbols, Zapf Dingbats or Braille. |
f979aebc | 625 | (You might want to visit L<http://www.unicode.org/> for a look at some of |
34babc16 JH |
626 | them - my personal favourites are Telugu and Kannada.) |
627 | ||
628 | The Unicode character sets associates characters with integers. Encoding | |
629 | these numbers in an equal number of bytes would more than double the | |
47b6252e | 630 | requirements for storing texts written in Latin alphabets. |
34babc16 JH |
631 | The UTF-8 encoding avoids this by storing the most common (from a western |
632 | point of view) characters in a single byte while encoding the rarer | |
633 | ones in three or more bytes. | |
634 | ||
2575c402 JW |
635 | Perl uses UTF-8, internally, for most Unicode strings. |
636 | ||
637 | So what has this got to do with C<pack>? Well, if you want to compose a | |
638 | Unicode string (that is internally encoded as UTF-8), you can do so by | |
639 | using template code C<U>. As an example, let's produce the Euro currency | |
640 | symbol (code number 0x20AC): | |
34babc16 JH |
641 | |
642 | $UTF8{Euro} = pack( 'U', 0x20AC ); | |
2575c402 | 643 | # Equivalent to: $UTF8{Euro} = "\x{20ac}"; |
34babc16 | 644 | |
2575c402 JW |
645 | Inspecting C<$UTF8{Euro}> shows that it contains 3 bytes: |
646 | "\xe2\x82\xac". However, it contains only 1 character, number 0x20AC. | |
647 | The round trip can be completed with C<unpack>: | |
34babc16 JH |
648 | |
649 | $Unicode{Euro} = unpack( 'U', $UTF8{Euro} ); | |
650 | ||
2575c402 JW |
651 | Unpacking using the C<U> template code also works on UTF-8 encoded byte |
652 | strings. | |
653 | ||
34babc16 JH |
654 | Usually you'll want to pack or unpack UTF-8 strings: |
655 | ||
656 | # pack and unpack the Hebrew alphabet | |
657 | my $alefbet = pack( 'U*', 0x05d0..0x05ea ); | |
658 | my @hebrew = unpack( 'U*', $utf ); | |
659 | ||
2575c402 JW |
660 | Please note: in the general case, you're better off using |
661 | Encode::decode_utf8 to decode a UTF-8 encoded byte string to a Perl | |
38a44b82 | 662 | Unicode string, and Encode::encode_utf8 to encode a Perl Unicode string |
2575c402 JW |
663 | to UTF-8 bytes. These functions provide means of handling invalid byte |
664 | sequences and generally have a friendlier interface. | |
34babc16 | 665 | |
47f22e19 WL |
666 | =head2 Another Portable Binary Encoding |
667 | ||
668 | The pack code C<w> has been added to support a portable binary data | |
669 | encoding scheme that goes way beyond simple integers. (Details can | |
f979aebc | 670 | be found at L<http://Casbah.org/>, the Scarab project.) A BER (Binary Encoded |
47f22e19 WL |
671 | Representation) compressed unsigned integer stores base 128 |
672 | digits, most significant digit first, with as few digits as possible. | |
673 | Bit eight (the high bit) is set on each byte except the last. There | |
674 | is no size limit to BER encoding, but Perl won't go to extremes. | |
675 | ||
676 | my $berbuf = pack( 'w*', 1, 128, 128+1, 128*128+127 ); | |
677 | ||
678 | A hex dump of C<$berbuf>, with spaces inserted at the right places, | |
679 | shows 01 8100 8101 81807F. Since the last byte is always less than | |
680 | 128, C<unpack> knows where to stop. | |
681 | ||
34babc16 | 682 | |
49704364 WL |
683 | =head1 Template Grouping |
684 | ||
685 | Prior to Perl 5.8, repetitions of templates had to be made by | |
686 | C<x>-multiplication of template strings. Now there is a better way as | |
687 | we may use the pack codes C<(> and C<)> combined with a repeat count. | |
688 | The C<unpack> template from the Stack Frame example can simply | |
689 | be written like this: | |
690 | ||
691 | unpack( 'v2 (vXXCC)5 v5', $frame ) | |
692 | ||
693 | Let's explore this feature a little more. We'll begin with the equivalent of | |
694 | ||
695 | join( '', map( substr( $_, 0, 1 ), @str ) ) | |
696 | ||
697 | which returns a string consisting of the first character from each string. | |
698 | Using pack, we can write | |
699 | ||
700 | pack( '(A)'.@str, @str ) | |
701 | ||
702 | or, because a repeat count C<*> means "repeat as often as required", | |
703 | simply | |
704 | ||
705 | pack( '(A)*', @str ) | |
706 | ||
707 | (Note that the template C<A*> would only have packed C<$str[0]> in full | |
708 | length.) | |
ffc145e8 | 709 | |
49704364 WL |
710 | To pack dates stored as triplets ( day, month, year ) in an array C<@dates> |
711 | into a sequence of byte, byte, short integer we can write | |
712 | ||
713 | $pd = pack( '(CCS)*', map( @$_, @dates ) ); | |
714 | ||
715 | To swap pairs of characters in a string (with even length) one could use | |
716 | several techniques. First, let's use C<x> and C<X> to skip forward and back: | |
717 | ||
718 | $s = pack( '(A)*', unpack( '(xAXXAx)*', $s ) ); | |
719 | ||
720 | We can also use C<@> to jump to an offset, with 0 being the position where | |
721 | we were when the last C<(> was encountered: | |
722 | ||
723 | $s = pack( '(A)*', unpack( '(@1A @0A @2)*', $s ) ); | |
724 | ||
725 | Finally, there is also an entirely different approach by unpacking big | |
726 | endian shorts and packing them in the reverse byte order: | |
727 | ||
728 | $s = pack( '(v)*', unpack( '(n)*', $s ); | |
729 | ||
730 | ||
34babc16 JH |
731 | =head1 Lengths and Widths |
732 | ||
733 | =head2 String Lengths | |
734 | ||
735 | In the previous section we've seen a network message that was constructed | |
736 | by prefixing the binary message length to the actual message. You'll find | |
737 | that packing a length followed by so many bytes of data is a | |
738 | frequently used recipe since appending a null byte won't work | |
47b6252e | 739 | if a null byte may be part of the data. Here is an example where both |
34babc16 JH |
740 | techniques are used: after two null terminated strings with source and |
741 | destination address, a Short Message (to a mobile phone) is sent after | |
742 | a length byte: | |
743 | ||
744 | my $msg = pack( 'Z*Z*CA*', $src, $dst, length( $sm ), $sm ); | |
745 | ||
746 | Unpacking this message can be done with the same template: | |
747 | ||
748 | ( $src, $dst, $len, $sm ) = unpack( 'Z*Z*CA*', $msg ); | |
749 | ||
47b6252e | 750 | There's a subtle trap lurking in the offing: Adding another field after |
34babc16 JH |
751 | the Short Message (in variable C<$sm>) is all right when packing, but this |
752 | cannot be unpacked naively: | |
753 | ||
754 | # pack a message | |
755 | my $msg = pack( 'Z*Z*CA*C', $src, $dst, length( $sm ), $sm, $prio ); | |
7207e29d | 756 | |
34babc16 JH |
757 | # unpack fails - $prio remains undefined! |
758 | ( $src, $dst, $len, $sm, $prio ) = unpack( 'Z*Z*CA*C', $msg ); | |
759 | ||
760 | The pack code C<A*> gobbles up all remaining bytes, and C<$prio> remains | |
761 | undefined! Before we let disappointment dampen the morale: Perl's got | |
762 | the trump card to make this trick too, just a little further up the sleeve. | |
763 | Watch this: | |
764 | ||
765 | # pack a message: ASCIIZ, ASCIIZ, length/string, byte | |
766 | my $msg = pack( 'Z* Z* C/A* C', $src, $dst, $sm, $prio ); | |
767 | ||
768 | # unpack | |
769 | ( $src, $dst, $sm, $prio ) = unpack( 'Z* Z* C/A* C', $msg ); | |
770 | ||
771 | Combining two pack codes with a slash (C</>) associates them with a single | |
772 | value from the argument list. In C<pack>, the length of the argument is | |
773 | taken and packed according to the first code while the argument itself | |
774 | is added after being converted with the template code after the slash. | |
775 | This saves us the trouble of inserting the C<length> call, but it is | |
776 | in C<unpack> where we really score: The value of the length byte marks the | |
777 | end of the string to be taken from the buffer. Since this combination | |
f8b4d74f | 778 | doesn't make sense except when the second pack code isn't C<a*>, C<A*> |
34babc16 JH |
779 | or C<Z*>, Perl won't let you. |
780 | ||
781 | The pack code preceding C</> may be anything that's fit to represent a | |
782 | number: All the numeric binary pack codes, and even text codes such as | |
783 | C<A4> or C<Z*>: | |
784 | ||
785 | # pack/unpack a string preceded by its length in ASCII | |
786 | my $buf = pack( 'A4/A*', "Humpty-Dumpty" ); | |
787 | # unpack $buf: '13 Humpty-Dumpty' | |
788 | my $txt = unpack( 'A4/A*', $buf ); | |
789 | ||
47b6252e NC |
790 | C</> is not implemented in Perls before 5.6, so if your code is required to |
791 | work on older Perls you'll need to C<unpack( 'Z* Z* C')> to get the length, | |
792 | then use it to make a new unpack string. For example | |
793 | ||
794 | # pack a message: ASCIIZ, ASCIIZ, length, string, byte (5.005 compatible) | |
795 | my $msg = pack( 'Z* Z* C A* C', $src, $dst, length $sm, $sm, $prio ); | |
796 | ||
797 | # unpack | |
798 | ( undef, undef, $len) = unpack( 'Z* Z* C', $msg ); | |
799 | ($src, $dst, $sm, $prio) = unpack ( "Z* Z* x A$len C", $msg ); | |
800 | ||
801 | But that second C<unpack> is rushing ahead. It isn't using a simple literal | |
802 | string for the template. So maybe we should introduce... | |
34babc16 JH |
803 | |
804 | =head2 Dynamic Templates | |
805 | ||
806 | So far, we've seen literals used as templates. If the list of pack | |
807 | items doesn't have fixed length, an expression constructing the | |
49704364 WL |
808 | template is required (whenever, for some reason, C<()*> cannot be used). |
809 | Here's an example: To store named string values in a way that can be | |
810 | conveniently parsed by a C program, we create a sequence of names and | |
811 | null terminated ASCII strings, with C<=> between the name and the value, | |
812 | followed by an additional delimiting null byte. Here's how: | |
34babc16 | 813 | |
49704364 | 814 | my $env = pack( '(A*A*Z*)' . keys( %Env ) . 'C', |
47f22e19 WL |
815 | map( { ( $_, '=', $Env{$_} ) } keys( %Env ) ), 0 ); |
816 | ||
817 | Let's examine the cogs of this byte mill, one by one. There's the C<map> | |
818 | call, creating the items we intend to stuff into the C<$env> buffer: | |
819 | to each key (in C<$_>) it adds the C<=> separator and the hash entry value. | |
820 | Each triplet is packed with the template code sequence C<A*A*Z*> that | |
49704364 | 821 | is repeated according to the number of keys. (Yes, that's what the C<keys> |
fe854a6f | 822 | function returns in scalar context.) To get the very last null byte, |
47f22e19 WL |
823 | we add a C<0> at the end of the C<pack> list, to be packed with C<C>. |
824 | (Attentive readers may have noticed that we could have omitted the 0.) | |
34babc16 JH |
825 | |
826 | For the reverse operation, we'll have to determine the number of items | |
827 | in the buffer before we can let C<unpack> rip it apart: | |
828 | ||
47b6252e | 829 | my $n = $env =~ tr/\0// - 1; |
49704364 | 830 | my %env = map( split( /=/, $_ ), unpack( "(Z*)$n", $env ) ); |
34babc16 | 831 | |
47b6252e | 832 | The C<tr> counts the null bytes. The C<unpack> call returns a list of |
47f22e19 | 833 | name-value pairs each of which is taken apart in the C<map> block. |
34babc16 JH |
834 | |
835 | ||
49704364 WL |
836 | =head2 Counting Repetitions |
837 | ||
838 | Rather than storing a sentinel at the end of a data item (or a list of items), | |
839 | we could precede the data with a count. Again, we pack keys and values of | |
840 | a hash, preceding each with an unsigned short length count, and up front | |
841 | we store the number of pairs: | |
842 | ||
843 | my $env = pack( 'S(S/A* S/A*)*', scalar keys( %Env ), %Env ); | |
844 | ||
845 | This simplifies the reverse operation as the number of repetitions can be | |
846 | unpacked with the C</> code: | |
847 | ||
848 | my %env = unpack( 'S/(S/A* S/A*)', $env ); | |
849 | ||
850 | Note that this is one of the rare cases where you cannot use the same | |
851 | template for C<pack> and C<unpack> because C<pack> can't determine | |
852 | a repeat count for a C<()>-group. | |
853 | ||
854 | ||
aa51dd41 MB |
855 | =head2 Intel HEX |
856 | ||
857 | Intel HEX is a file format for representing binary data, mostly for | |
858 | programming various chips, as a text file. (See | |
859 | L<http://en.wikipedia.org/wiki/.hex> for a detailed description, and | |
860 | L<http://en.wikipedia.org/wiki/SREC_(file_format)> for the Motorola | |
861 | S-record format, which can be unravelled using the same technique.) | |
862 | Each line begins with a colon (':') and is followed by a sequence of | |
863 | hexadecimal characters, specifying a byte count I<n> (8 bit), | |
864 | an address (16 bit, big endian), a record type (8 bit), I<n> data bytes | |
865 | and a checksum (8 bit) computed as the least significant byte of the two's | |
866 | complement sum of the preceding bytes. Example: C<:0300300002337A1E>. | |
867 | ||
868 | The first step of processing such a line is the conversion, to binary, | |
869 | of the hexadecimal data, to obtain the four fields, while checking the | |
870 | checksum. No surprise here: we'll start with a simple C<pack> call to | |
871 | convert everything to binary: | |
872 | ||
873 | my $binrec = pack( 'H*', substr( $hexrec, 1 ) ); | |
874 | ||
875 | The resulting byte sequence is most convenient for checking the checksum. | |
876 | Don't slow your program down with a for loop adding the C<ord> values | |
877 | of this string's bytes - the C<unpack> code C<%> is the thing to use | |
878 | for computing the 8-bit sum of all bytes, which must be equal to zero: | |
879 | ||
880 | die unless unpack( "%8C*", $binrec ) == 0; | |
881 | ||
882 | Finally, let's get those four fields. By now, you shouldn't have any | |
883 | problems with the first three fields - but how can we use the byte count | |
884 | of the data in the first field as a length for the data field? Here | |
885 | the codes C<x> and C<X> come to the rescue, as they permit jumping | |
886 | back and forth in the string to unpack. | |
887 | ||
888 | my( $addr, $type, $data ) = unpack( "x n C X4 C x3 /a", $bin ); | |
889 | ||
890 | Code C<x> skips a byte, since we don't need the count yet. Code C<n> takes | |
891 | care of the 16-bit big-endian integer address, and C<C> unpacks the | |
892 | record type. Being at offset 4, where the data begins, we need the count. | |
893 | C<X4> brings us back to square one, which is the byte at offset 0. | |
894 | Now we pick up the count, and zoom forth to offset 4, where we are | |
895 | now fully furnished to extract the exact number of data bytes, leaving | |
896 | the trailing checksum byte alone. | |
897 | ||
898 | ||
899 | ||
34babc16 JH |
900 | =head1 Packing and Unpacking C Structures |
901 | ||
902 | In previous sections we have seen how to pack numbers and character | |
903 | strings. If it were not for a couple of snags we could conclude this | |
904 | section right away with the terse remark that C structures don't | |
905 | contain anything else, and therefore you already know all there is to it. | |
906 | Sorry, no: read on, please. | |
907 | ||
59f20ca5 MHM |
908 | If you have to deal with a lot of C structures, and don't want to |
909 | hack all your template strings manually, you'll probably want to have | |
910 | a look at the CPAN module C<Convert::Binary::C>. Not only can it parse | |
911 | your C source directly, but it also has built-in support for all the | |
912 | odds and ends described further on in this section. | |
913 | ||
34babc16 JH |
914 | =head2 The Alignment Pit |
915 | ||
916 | In the consideration of speed against memory requirements the balance | |
917 | has been tilted in favor of faster execution. This has influenced the | |
918 | way C compilers allocate memory for structures: On architectures | |
919 | where a 16-bit or 32-bit operand can be moved faster between places in | |
920 | memory, or to or from a CPU register, if it is aligned at an even or | |
921 | multiple-of-four or even at a multiple-of eight address, a C compiler | |
922 | will give you this speed benefit by stuffing extra bytes into structures. | |
923 | If you don't cross the C shoreline this is not likely to cause you any | |
47b6252e NC |
924 | grief (although you should care when you design large data structures, |
925 | or you want your code to be portable between architectures (you do want | |
926 | that, don't you?)). | |
34babc16 JH |
927 | |
928 | To see how this affects C<pack> and C<unpack>, we'll compare these two | |
929 | C structures: | |
930 | ||
931 | typedef struct { | |
932 | char c1; | |
933 | short s; | |
934 | char c2; | |
935 | long l; | |
936 | } gappy_t; | |
937 | ||
938 | typedef struct { | |
939 | long l; | |
940 | short s; | |
941 | char c1; | |
942 | char c2; | |
943 | } dense_t; | |
944 | ||
945 | Typically, a C compiler allocates 12 bytes to a C<gappy_t> variable, but | |
946 | requires only 8 bytes for a C<dense_t>. After investigating this further, | |
947 | we can draw memory maps, showing where the extra 4 bytes are hidden: | |
948 | ||
949 | 0 +4 +8 +12 | |
950 | +--+--+--+--+--+--+--+--+--+--+--+--+ | |
951 | |c1|xx| s |c2|xx|xx|xx| l | xx = fill byte | |
952 | +--+--+--+--+--+--+--+--+--+--+--+--+ | |
953 | gappy_t | |
954 | ||
955 | 0 +4 +8 | |
956 | +--+--+--+--+--+--+--+--+ | |
957 | | l | h |c1|c2| | |
958 | +--+--+--+--+--+--+--+--+ | |
959 | dense_t | |
960 | ||
961 | And that's where the first quirk strikes: C<pack> and C<unpack> | |
962 | templates have to be stuffed with C<x> codes to get those extra fill bytes. | |
963 | ||
964 | The natural question: "Why can't Perl compensate for the gaps?" warrants | |
965 | an answer. One good reason is that C compilers might provide (non-ANSI) | |
966 | extensions permitting all sorts of fancy control over the way structures | |
967 | are aligned, even at the level of an individual structure field. And, if | |
968 | this were not enough, there is an insidious thing called C<union> where | |
969 | the amount of fill bytes cannot be derived from the alignment of the next | |
970 | item alone. | |
971 | ||
972 | OK, so let's bite the bullet. Here's one way to get the alignment right | |
973 | by inserting template codes C<x>, which don't take a corresponding item | |
974 | from the list: | |
975 | ||
976 | my $gappy = pack( 'cxs cxxx l!', $c1, $s, $c2, $l ); | |
977 | ||
978 | Note the C<!> after C<l>: We want to make sure that we pack a long | |
47b6252e NC |
979 | integer as it is compiled by our C compiler. And even now, it will only |
980 | work for the platforms where the compiler aligns things as above. | |
981 | And somebody somewhere has a platform where it doesn't. | |
982 | [Probably a Cray, where C<short>s, C<int>s and C<long>s are all 8 bytes. :-)] | |
34babc16 JH |
983 | |
984 | Counting bytes and watching alignments in lengthy structures is bound to | |
985 | be a drag. Isn't there a way we can create the template with a simple | |
986 | program? Here's a C program that does the trick: | |
987 | ||
988 | #include <stdio.h> | |
989 | #include <stddef.h> | |
990 | ||
991 | typedef struct { | |
992 | char fc1; | |
993 | short fs; | |
994 | char fc2; | |
995 | long fl; | |
996 | } gappy_t; | |
997 | ||
998 | #define Pt(struct,field,tchar) \ | |
999 | printf( "@%d%s ", offsetof(struct,field), # tchar ); | |
1000 | ||
d832b8f6 | 1001 | int main() { |
34babc16 JH |
1002 | Pt( gappy_t, fc1, c ); |
1003 | Pt( gappy_t, fs, s! ); | |
1004 | Pt( gappy_t, fc2, c ); | |
1005 | Pt( gappy_t, fl, l! ); | |
1006 | printf( "\n" ); | |
1007 | } | |
1008 | ||
1009 | The output line can be used as a template in a C<pack> or C<unpack> call: | |
1010 | ||
1011 | my $gappy = pack( '@0c @2s! @4c @8l!', $c1, $s, $c2, $l ); | |
1012 | ||
1013 | Gee, yet another template code - as if we hadn't plenty. But | |
1014 | C<@> saves our day by enabling us to specify the offset from the beginning | |
1015 | of the pack buffer to the next item: This is just the value | |
1016 | the C<offsetof> macro (defined in C<E<lt>stddef.hE<gt>>) returns when | |
1017 | given a C<struct> type and one of its field names ("member-designator" in | |
1018 | C standardese). | |
1019 | ||
49704364 WL |
1020 | Neither using offsets nor adding C<x>'s to bridge the gaps is satisfactory. |
1021 | (Just imagine what happens if the structure changes.) What we really need | |
1022 | is a way of saying "skip as many bytes as required to the next multiple of N". | |
1023 | In fluent Templatese, you say this with C<x!N> where N is replaced by the | |
1024 | appropriate value. Here's the next version of our struct packaging: | |
1025 | ||
1026 | my $gappy = pack( 'c x!2 s c x!4 l!', $c1, $s, $c2, $l ); | |
1027 | ||
1028 | That's certainly better, but we still have to know how long all the | |
1029 | integers are, and portability is far away. Rather than C<2>, | |
1030 | for instance, we want to say "however long a short is". But this can be | |
1031 | done by enclosing the appropriate pack code in brackets: C<[s]>. So, here's | |
1032 | the very best we can do: | |
1033 | ||
1034 | my $gappy = pack( 'c x![s] s c x![l!] l!', $c1, $s, $c2, $l ); | |
1035 | ||
34babc16 | 1036 | |
59f20ca5 MHM |
1037 | =head2 Dealing with Endian-ness |
1038 | ||
1039 | Now, imagine that we want to pack the data for a machine with a | |
1040 | different byte-order. First, we'll have to figure out how big the data | |
1041 | types on the target machine really are. Let's assume that the longs are | |
1042 | 32 bits wide and the shorts are 16 bits wide. You can then rewrite the | |
1043 | template as: | |
1044 | ||
1045 | my $gappy = pack( 'c x![s] s c x![l] l', $c1, $s, $c2, $l ); | |
1046 | ||
1047 | If the target machine is little-endian, we could write: | |
1048 | ||
1049 | my $gappy = pack( 'c x![s] s< c x![l] l<', $c1, $s, $c2, $l ); | |
1050 | ||
1051 | This forces the short and the long members to be little-endian, and is | |
1052 | just fine if you don't have too many struct members. But we could also | |
1053 | use the byte-order modifier on a group and write the following: | |
1054 | ||
1055 | my $gappy = pack( '( c x![s] s c x![l] l )<', $c1, $s, $c2, $l ); | |
1056 | ||
1057 | This is not as short as before, but it makes it more obvious that we | |
1058 | intend to have little-endian byte-order for a whole group, not only | |
1059 | for individual template codes. It can also be more readable and easier | |
1060 | to maintain. | |
1061 | ||
1062 | ||
34babc16 JH |
1063 | =head2 Alignment, Take 2 |
1064 | ||
1065 | I'm afraid that we're not quite through with the alignment catch yet. The | |
1066 | hydra raises another ugly head when you pack arrays of structures: | |
1067 | ||
1068 | typedef struct { | |
1069 | short count; | |
1070 | char glyph; | |
1071 | } cell_t; | |
1072 | ||
1073 | typedef cell_t buffer_t[BUFLEN]; | |
1074 | ||
1075 | Where's the catch? Padding is neither required before the first field C<count>, | |
1076 | nor between this and the next field C<glyph>, so why can't we simply pack | |
1077 | like this: | |
1078 | ||
1079 | # something goes wrong here: | |
1080 | pack( 's!a' x @buffer, | |
1081 | map{ ( $_->{count}, $_->{glyph} ) } @buffer ); | |
1082 | ||
1083 | This packs C<3*@buffer> bytes, but it turns out that the size of | |
1084 | C<buffer_t> is four times C<BUFLEN>! The moral of the story is that | |
1085 | the required alignment of a structure or array is propagated to the | |
1086 | next higher level where we have to consider padding I<at the end> | |
1087 | of each component as well. Thus the correct template is: | |
1088 | ||
1089 | pack( 's!ax' x @buffer, | |
1090 | map{ ( $_->{count}, $_->{glyph} ) } @buffer ); | |
1091 | ||
47b6252e NC |
1092 | =head2 Alignment, Take 3 |
1093 | ||
1094 | And even if you take all the above into account, ANSI still lets this: | |
1095 | ||
1096 | typedef struct { | |
1097 | char foo[2]; | |
1098 | } foo_t; | |
34babc16 | 1099 | |
47b6252e NC |
1100 | vary in size. The alignment constraint of the structure can be greater than |
1101 | any of its elements. [And if you think that this doesn't affect anything | |
1102 | common, dismember the next cellphone that you see. Many have ARM cores, and | |
1103 | the ARM structure rules make C<sizeof (foo_t)> == 4] | |
34babc16 JH |
1104 | |
1105 | =head2 Pointers for How to Use Them | |
1106 | ||
1107 | The title of this section indicates the second problem you may run into | |
1108 | sooner or later when you pack C structures. If the function you intend | |
1109 | to call expects a, say, C<void *> value, you I<cannot> simply take | |
1110 | a reference to a Perl variable. (Although that value certainly is a | |
1111 | memory address, it's not the address where the variable's contents are | |
1112 | stored.) | |
1113 | ||
1114 | Template code C<P> promises to pack a "pointer to a fixed length string". | |
1115 | Isn't this what we want? Let's try: | |
1116 | ||
1117 | # allocate some storage and pack a pointer to it | |
1118 | my $memory = "\x00" x $size; | |
1119 | my $memptr = pack( 'P', $memory ); | |
1120 | ||
1121 | But wait: doesn't C<pack> just return a sequence of bytes? How can we pass this | |
1122 | string of bytes to some C code expecting a pointer which is, after all, | |
1123 | nothing but a number? The answer is simple: We have to obtain the numeric | |
1124 | address from the bytes returned by C<pack>. | |
1125 | ||
1126 | my $ptr = unpack( 'L!', $memptr ); | |
1127 | ||
1128 | Obviously this assumes that it is possible to typecast a pointer | |
1129 | to an unsigned long and vice versa, which frequently works but should not | |
1130 | be taken as a universal law. - Now that we have this pointer the next question | |
1131 | is: How can we put it to good use? We need a call to some C function | |
1132 | where a pointer is expected. The read(2) system call comes to mind: | |
1133 | ||
1134 | ssize_t read(int fd, void *buf, size_t count); | |
1135 | ||
1136 | After reading L<perlfunc> explaining how to use C<syscall> we can write | |
1137 | this Perl function copying a file to standard output: | |
1138 | ||
1139 | require 'syscall.ph'; | |
1140 | sub cat($){ | |
1141 | my $path = shift(); | |
1142 | my $size = -s $path; | |
1143 | my $memory = "\x00" x $size; # allocate some memory | |
1144 | my $ptr = unpack( 'L', pack( 'P', $memory ) ); | |
1145 | open( F, $path ) || die( "$path: cannot open ($!)\n" ); | |
1146 | my $fd = fileno(F); | |
1147 | my $res = syscall( &SYS_read, fileno(F), $ptr, $size ); | |
1148 | print $memory; | |
1149 | close( F ); | |
1150 | } | |
1151 | ||
1152 | This is neither a specimen of simplicity nor a paragon of portability but | |
1153 | it illustrates the point: We are able to sneak behind the scenes and | |
1154 | access Perl's otherwise well-guarded memory! (Important note: Perl's | |
1155 | C<syscall> does I<not> require you to construct pointers in this roundabout | |
1156 | way. You simply pass a string variable, and Perl forwards the address.) | |
1157 | ||
1158 | How does C<unpack> with C<P> work? Imagine some pointer in the buffer | |
1159 | about to be unpacked: If it isn't the null pointer (which will smartly | |
1160 | produce the C<undef> value) we have a start address - but then what? | |
1161 | Perl has no way of knowing how long this "fixed length string" is, so | |
1162 | it's up to you to specify the actual size as an explicit length after C<P>. | |
1163 | ||
1164 | my $mem = "abcdefghijklmn"; | |
1165 | print unpack( 'P5', pack( 'P', $mem ) ); # prints "abcde" | |
1166 | ||
1167 | As a consequence, C<pack> ignores any number or C<*> after C<P>. | |
1168 | ||
1169 | ||
1170 | Now that we have seen C<P> at work, we might as well give C<p> a whirl. | |
1171 | Why do we need a second template code for packing pointers at all? The | |
1172 | answer lies behind the simple fact that an C<unpack> with C<p> promises | |
1173 | a null-terminated string starting at the address taken from the buffer, | |
1174 | and that implies a length for the data item to be returned: | |
1175 | ||
1176 | my $buf = pack( 'p', "abc\x00efhijklmn" ); | |
1177 | print unpack( 'p', $buf ); # prints "abc" | |
1178 | ||
1179 | ||
1180 | ||
1181 | Albeit this is apt to be confusing: As a consequence of the length being | |
1182 | implied by the string's length, a number after pack code C<p> is a repeat | |
1183 | count, not a length as after C<P>. | |
1184 | ||
1185 | ||
1186 | Using C<pack(..., $x)> with C<P> or C<p> to get the address where C<$x> is | |
1187 | actually stored must be used with circumspection. Perl's internal machinery | |
1188 | considers the relation between a variable and that address as its very own | |
1189 | private matter and doesn't really care that we have obtained a copy. Therefore: | |
1190 | ||
1191 | =over 4 | |
1192 | ||
1193 | =item * | |
1194 | ||
1195 | Do not use C<pack> with C<p> or C<P> to obtain the address of variable | |
1196 | that's bound to go out of scope (and thereby freeing its memory) before you | |
1197 | are done with using the memory at that address. | |
1198 | ||
1199 | =item * | |
1200 | ||
1201 | Be very careful with Perl operations that change the value of the | |
1202 | variable. Appending something to the variable, for instance, might require | |
1203 | reallocation of its storage, leaving you with a pointer into no-man's land. | |
1204 | ||
1205 | =item * | |
1206 | ||
1207 | Don't think that you can get the address of a Perl variable | |
1208 | when it is stored as an integer or double number! C<pack('P', $x)> will | |
1209 | force the variable's internal representation to string, just as if you | |
1210 | had written something like C<$x .= ''>. | |
1211 | ||
1212 | =back | |
1213 | ||
1214 | It's safe, however, to P- or p-pack a string literal, because Perl simply | |
1215 | allocates an anonymous variable. | |
1216 | ||
1217 | ||
1218 | ||
1219 | =head1 Pack Recipes | |
1220 | ||
1221 | Here are a collection of (possibly) useful canned recipes for C<pack> | |
1222 | and C<unpack>: | |
1223 | ||
1224 | # Convert IP address for socket functions | |
1225 | pack( "C4", split /\./, "123.4.5.6" ); | |
1226 | ||
1227 | # Count the bits in a chunk of memory (e.g. a select vector) | |
1228 | unpack( '%32b*', $mask ); | |
1229 | ||
1230 | # Determine the endianness of your system | |
1231 | $is_little_endian = unpack( 'c', pack( 's', 1 ) ); | |
1232 | $is_big_endian = unpack( 'xc', pack( 's', 1 ) ); | |
1233 | ||
1234 | # Determine the number of bits in a native integer | |
1235 | $bits = unpack( '%32I!', ~0 ); | |
1236 | ||
1237 | # Prepare argument for the nanosleep system call | |
1238 | my $timespec = pack( 'L!L!', $secs, $nanosecs ); | |
1239 | ||
f8b4d74f WL |
1240 | For a simple memory dump we unpack some bytes into just as |
1241 | many pairs of hex digits, and use C<map> to handle the traditional | |
1242 | spacing - 16 bytes to a line: | |
1243 | ||
34babc16 | 1244 | my $i; |
49704364 WL |
1245 | print map( ++$i % 16 ? "$_ " : "$_\n", |
1246 | unpack( 'H2' x length( $mem ), $mem ) ), | |
f8b4d74f | 1247 | length( $mem ) % 16 ? "\n" : ''; |
34babc16 JH |
1248 | |
1249 | ||
47f22e19 WL |
1250 | =head1 Funnies Section |
1251 | ||
1252 | # Pulling digits out of nowhere... | |
1253 | print unpack( 'C', pack( 'x' ) ), | |
1254 | unpack( '%B*', pack( 'A' ) ), | |
1255 | unpack( 'H', pack( 'A' ) ), | |
1256 | unpack( 'A', unpack( 'C', pack( 'A' ) ) ), "\n"; | |
1257 | ||
1258 | # One for the road ;-) | |
1259 | my $advice = pack( 'all u can in a van' ); | |
1260 | ||
1261 | ||
34babc16 JH |
1262 | =head1 Authors |
1263 | ||
1264 | Simon Cozens and Wolfgang Laun. | |
1265 |