pack

(PHP 4, PHP 5, PHP 7, PHP 8)

pack將數(shù)據(jù)打包成二進制字符串

說明

pack(string $format, mixed ...$values): string

將輸入?yún)?shù)打包成 format 格式的二進制字符串。

這個函數(shù)的思想來自 Perl,所有格式化代碼(format)的工作原理都與 Perl 相同。 但是,缺少了部分格式代碼,比如 Perl 的 “u”。

注意,有符號值和無符號值之間的區(qū)別只影響函數(shù) unpack(),在那些使用有符號和無符號格式代碼的地方 pack() 函數(shù)產生相同的結果。

參數(shù)

format

format 字符串由格式代碼組成,后面跟著一個可選的重復參數(shù)。重復參數(shù)可以是一個整數(shù)值或者 * 值來重復到輸入數(shù)據(jù)的末尾。對于 a, A, h, H 格式化代碼,其后的重復參數(shù)指定了給定數(shù)據(jù)將會被使用幾個字符串。對于 @,其后的數(shù)字表示放置剩余數(shù)據(jù)的絕對定位(之前的數(shù)據(jù)將會被空字符串填充),對于其他所有內容,重復數(shù)量指定消耗多少個數(shù)據(jù)參數(shù)并將其打包到生成的二進制字符串中。

目前已實現(xiàn)的格式如下:

pack() 格式字符
代碼 描述
a 以 NUL 字節(jié)填充字符串
A 以 SPACE(空格) 填充字符串
h 十六進制字符串,低位在前
H 十六進制字符串,高位在前
c有符號字符
C 無符號字符
s 有符號短整型(16位,主機字節(jié)序)
S 無符號短整型(16位,主機字節(jié)序)
n 無符號短整型(16位,大端字節(jié)序)
v 無符號短整型(16位,小端字節(jié)序)
i 有符號整型(機器相關大小字節(jié)序)
I 無符號整型(機器相關大小字節(jié)序)
l 有符號長整型(32位,主機字節(jié)序)
L 無符號長整型(32位,主機字節(jié)序)
N 無符號長整型(32位,大端字節(jié)序)
V 無符號長整型(32位,小端字節(jié)序)
q 有符號長長整型(64位,主機字節(jié)序)
Q 無符號長長整型(64位,主機字節(jié)序)
J 無符號長長整型(64位,大端字節(jié)序)
P 無符號長長整型(64位,小端字節(jié)序)
f 單精度浮點型(機器相關大小)
g 單精度浮點型(機器相關大小,小端字節(jié)序)
G 單精度浮點型(機器相關大小,大端字節(jié)序)
d 雙精度浮點型(機器相關大小)
e 雙精度浮點型(機器相關大小,小端字節(jié)序)
E 雙精度浮點型(機器相關大小,大端字節(jié)序)
x NUL 字節(jié)
X 回退一字節(jié)
Z 以 NUL 字節(jié)填充字符串空白
@ NUL 填充到絕對位置

values

返回值

返回包含數(shù)據(jù)的二進制字符串, 或者在失敗時返回 false

更新日志

版本 說明
8.0.0 此函數(shù)不再在失敗時返回 false 。
7.2.0 floatdouble 類型支持大端和小端。
7.0.15,7.1.1 添加了 “e”,“E”,“g” 和 “G” 代碼以啟用 float 和 double 的字節(jié)順序支持。

范例

示例 #1 pack() 范例

<?php
$binarydata 
pack("nvc*"0x12340x56786566);
?>

輸出結果為長度為 6 字節(jié)的二進制字符串,包含以下序列 0x12, 0x34, 0x78, 0x56, 0x41, 0x42。

注釋

警告

Note that PHP internally stores int values as signed values of a machine-dependent size (C type long). Integer literals and operations that yield numbers outside the bounds of the int type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.

The most relevant case is when packing unsigned numbers that would be representable with the int type if it were unsigned. In systems where the int type has a 32-bit size, the cast usually results in the same byte pattern as if the int were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the int type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C int type (most UNIX-like systems don't), the only way to use the I pack format in the upper range is to create int negative values with the same byte representation as the desired unsigned value.

參見

  • unpack() - Unpack data from binary string