View Single Post
Old 04-20-2007, 05:08 PM   #20
Well past expiration date
tk102's Avatar
Join Date: Jan 2004
Posts: 5,768
Current Game: FTL
10 year veteran!  Forum Veteran  Helpful!  Notable contributor 
Originally Posted by stoffe
The unpack() function takes a string and splits it by token into an array, like explode() in PHP? While pack() takes an array and spits out a token-separated string from it?
No, The pack and unpack functions are Perl's way forcing data to/from certain interpretations like an unsigned long (template: V) or a unsigned byte (template: C). This is needed because of Perl's weak typing mechanisms. pack takes data forces it into a datatype while unpack translates coerced data back into perl scalars.

What does your reverse_bytes() function receive as parameter, a token-separated string (using "V" as separator) containing the three values a texel-struct holds?
reverse_bytes accepts a perl scalar (which itself was populated from an unpack function with template V). It then packs this value into an unsigned long again, unpacks it into 4 unsigned bytes, reverses the array of bytes, repacks the array of bytes, and then unpacks the result as unsigned long.

(As you don't have the source: The C++ code takes a struct as function parameter containing two 16 bit unsigned ints and one 32 bit unsigned int value... does something with those three values which I have absolutely no idea what, and then spits out a single 32 bit unsigned integer as result.)
Anyway the more elegant C++ code appears as this:
inline u32 reverse_bytes(u32 i, int2type<4>) {
	return    (i&0xFF000000) >> 24 
		| (i&0x00FF0000) >>  8
		| (i&0x0000FF00) <<  8
		| (i&0x000000FF) << 24;
Here you can see better the masking and data shifting involved. The perl code accomplishes the same thing but uses a temporary array of bytes that it reverses and repacks into a long then unpacks to get the numeric value.

* * *

Last edited by tk102; 04-20-2007 at 06:10 PM.
tk102 is offline   you may: quote & reply,