Core Function Pack
Pack( <format>, <args> )
Contents |
Description
Pack data into a binary array.
Pack given arguments into a binary string according to format.
Parameters
format
The format string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or * for repeating to the end of the input data.
For a, A, b, B, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.
You may place spaces in the format string and they will be stripped automatically so you can use them to make things more readable.
Currently implemented formats are:
Code Description a NUL-padded string A SPACE-padded string b A bit string (ascending bit order inside each byte, like the Vec() function) B A bit string (descending bit order inside each byte) h Hex string, low nibble first H Hex string, high nibble first c signed ASCII char C unsigned ASCII char U UNICODE char s signed short (always 16 bit, machine byte order) S unsigned short (always 16 bit, machine byte order) n unsigned short (always 16 bit, big endian byte order) v unsigned short (always 16 bit, little endian byte order) i signed integer (machine dependent size and byte order) I unsigned integer (machine dependent size and byte order) l signed long (always 32 bit, machine byte order) L unsigned long (always 32 bit, machine byte order) q signed quad (64-bit) value (always 64 bit, machine byte order) Q unsigned quad (64-bit) value (always 64 bit, machine byte order) N unsigned long (always 32 bit, big endian byte order) V unsigned long (always 32 bit, little endian byte order) f float (machine dependent size and representation) d double (machine dependent size and representation) x NUL byte X Back up one byte @ NUL-fill to absolute position
args
One or more variables to be used in the packing.
Return Value
Success: Returns the new binary variable.
Failure: Returns null.
Remarks
Note that Sputnik stores variables as signed/unsigned as needed which can be confusing if you are a PHP user using this Pack function basically when the format says Unsigned it is literal and the variable will be unsigned/signed as specified both the packing and unpacking.
This also means if the original value as an Int64 and you packed it with "i" then unpack it with "i" the new value will be an Int32 and not an Int64 since Sputnik sees no need to magically unpack everything to highest data type so "f" will actually give you a Float and not a Double and so on of course that doesn't mean you can't cast it to a double when getting from the return array.
Be aware that if you do not name an element, an empty string is used. If you do not name more than one element, this means that some data is overwritten as the keys are the same
Example
Using Pack() to format ASCII text in a readable way with everything correctly spaced out
// Make an array of people my $People = array(array("Name", "ID", "Birth", "Sex", "Race")); push($People, array("Mike", 0, "1980", "M", "German")); push($People, array("Tommy", 1, "1985", "M", "French")); push($People, array("David", 2, "1950", "M", "Jewish")); push($People, array("Sukara", 3, "1990", "F", "Japanese")); push($People, array("Mary-Kate", 4, "1987", "F", "American")); // Print them all in a nice formatted way foreach($People as $Person) { my List ( $Name, $ID, $Birth, $Sex, $Race ) = $Person; my $Sorted = pack("A12 A4 A7 A5 A*", $Name, $ID, $Birth, $Sex, $Race); echo "$Sorted\n"; } # Prints # Name ID Birth Sex Race # Mike 0 1980 M German # Tommy 1 1985 M French # David 2 1950 M Jewish # Sukara 3 1990 F Japanese # Mary-Kate 4 1987 F American
Using Unpack() to read from formatted ASCII text and extract information from it similar to Regex but much more reliable for this specific task
# Lets imagine this variable was loaded from a file # It contains information that is using specific spaces # to keep it organized so it can be displayed on the # company computers properly # We are going to read this information and process it # You could use regexp or splitting but they would be # impractical so lets use Unpack() instead my $data = " Date |Description | Income|Expenditure 01/24/2001 Zed's Camel Emporium 1147.99 01/28/2001 Flea spray 24.99 01/29/2001 Camel rides to tourists 235.00 01/29/2001 Tourist camel feedings 100.10 "; my $TotalIncome = 0.0; my $TotalExpenditure = 0.0; foreach(Lines($data) as $line) { if(isEmptyOrNull(trim($line))) continue; # Skip useless entries my List( $date, $desc, $income, $expend ) = unpack("A10/x/A27/x/A7/A*", $line); $income = trim($income); # Trim it so we can do arithmetics on it $expend = trim($expend); # Trim it so we can do arithmetics on it $TotalIncome += $income; $TotalExpenditure += $expend; # Print it just so prove we are reading it correctly other than that # it is pointless echo "Log: '$date' | '$desc' | '$income' | '$expend'\n"; } echo "Total income is: $TotalIncome\n"; echo "Total expenditure is: $TotalExpenditure\n"; # Prints: # Log: 'Date' | 'Description' | 'Income' | '|Expenditure' # Log: '01/24/2001' | 'Zed's Camel Emporium' | '' | '1147.99' # Log: '01/28/2001' | 'Flea spray' | '' | '24.99' # Log: '01/29/2001' | 'Camel rides to tourists' | '235.00' | '' # Log: '01/29/2001' | 'Tourist camel feedings' | '100.10' | '' # Total income is: 335.1 # Total expenditure is: 1172.98
Example of choosing names for KEY in the return array
$binarydata = "\x04\x00\xa0\x00"; $array = Unpack("cchars/nint", $binarydata); // The resulting array will contain the entries // "chars" with value 4 and "int" with 160. printr $array; // Prints: // ARRAY // { // [chars] => 4 // [int] => 194 // }
Same as above
$binarydata = "\x04\x00\xa0\x00"; $array = Unpack("c2chars/nint", $binarydata); // The resulting array will contain the entries // "chars1", "chars2" and "int". printr $array; // Prints: // ARRAY // { // [chars1] => 4 // [chars2] => 0 // [int] => 49824 // }
Packing a bunch of values at once
$binarydata = Pack("nvc*", 0x1234, 0x5678, 65, 66); // The resulting binary string will be 6 bytes long // and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42. printr $binarydata; // Prints: // {BINARY:6} // { // [0] => 18 // [1] => 52 // [2] => 120 // [3] => 86 // [4] => 65 // [5] => 66 // }
Using * to pack all the remaining objects with the same specifier
printr pack("C*",80,72,80);
String to Hex and back again
function H2Str( $hex ) { return pack('H*', $hex); } function Str2H( $str ) { return unpack('H*', $str, true); } $txt = 'This is test'; $hex = Str2H( $txt ); $str = H2Str( $hex ); echo "${txt} => ${hex} => ${str}\n";
Display the ASCII character codes for an entire string
echo join (unpack('C*', 'abcdef'), ' '); // 97 98 99 100 101 102
Display the UNICODE character codes for an entire string
echo join (unpack('U*', 'こんにちは'), ' '); // 33251 58259 37762 33251 58283 41345 33251