(PHP 4, PHP 5, PHP 7, PHP 8)
pack — 將數據打包成二進(jìn)制字符串
將輸入參數打包成 format
格式的二進(jìn)制字符串。
這個(gè)函數的思想來(lái)自 Perl,所有格式化代碼(format
)的工作原理都與
Perl 相同。 但是,缺少了部分格式代碼,比如 Perl 的 “u”。
注意,有符號值和無(wú)符號值之間的區別只影響函數 unpack(),在那些使用有符號和無(wú)符號格式代碼的地方 pack() 函數產(chǎn)生相同的結果。
format
format
字符串由格式代碼組成,后面跟著(zhù)一個(gè)可選的重復參數。重復參數可以是一個(gè)整數值或者
*
值來(lái)重復到輸入數據的末尾。對于 a, A, h, H
格式化代碼,其后的重復參數指定了給定數據將會(huì )被使用幾個(gè)字符串。對于
@,其后的數字表示放置剩余數據的絕對定位(之前的數據將會(huì )被空字符串填充),對于其他所有內容,重復數量指定消耗多少個(gè)數據參數并將其打包到生成的二進(jìn)制字符串中。
目前已實(shí)現的格式如下:
代碼 | 描述 |
---|---|
a | 以 NUL 字節填充字符串 |
A | 以 SPACE(空格) 填充字符串 |
h | 十六進(jìn)制字符串,低位在前 |
H | 十六進(jìn)制字符串,高位在前 |
c | 有符號字符 |
C | 無(wú)符號字符 |
s | 有符號短整型(16位,主機字節序) |
S | 無(wú)符號短整型(16位,主機字節序) |
n | 無(wú)符號短整型(16位,大端字節序) |
v | 無(wú)符號短整型(16位,小端字節序) |
i | 有符號整型(機器相關(guān)大小字節序) |
I | 無(wú)符號整型(機器相關(guān)大小字節序) |
l | 有符號長(cháng)整型(32位,主機字節序) |
L | 無(wú)符號長(cháng)整型(32位,主機字節序) |
N | 無(wú)符號長(cháng)整型(32位,大端字節序) |
V | 無(wú)符號長(cháng)整型(32位,小端字節序) |
q | 有符號長(cháng)長(cháng)整型(64位,主機字節序) |
Q | 無(wú)符號長(cháng)長(cháng)整型(64位,主機字節序) |
J | 無(wú)符號長(cháng)長(cháng)整型(64位,大端字節序) |
P | 無(wú)符號長(cháng)長(cháng)整型(64位,小端字節序) |
f | 單精度浮點(diǎn)型(機器相關(guān)大小) |
g | 單精度浮點(diǎn)型(機器相關(guān)大小,小端字節序) |
G | 單精度浮點(diǎn)型(機器相關(guān)大小,大端字節序) |
d | 雙精度浮點(diǎn)型(機器相關(guān)大小) |
e | 雙精度浮點(diǎn)型(機器相關(guān)大小,小端字節序) |
E | 雙精度浮點(diǎn)型(機器相關(guān)大小,大端字節序) |
x | NUL 字節 |
X | 回退一字節 |
Z | 以 NUL 字節填充字符串空白 |
@ | NUL 填充到絕對位置 |
values
返回包含數據的二進(jìn)制字符串, 或者在失敗時(shí)返回 false
。
版本 | 說(shuō)明 |
---|---|
8.0.0 |
此函數不再在失敗時(shí)返回 false 。
|
7.2.0 | float 和 double 類(lèi)型支持大端和小端。 |
7.0.15,7.1.1 | 添加了 “e”,“E”,“g” 和 “G” 代碼以啟用 float 和 double 的字節順序支持。 |
示例 #1 pack() 范例
<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>
輸出結果為長(cháng)度為 6 字節的二進(jìn)制字符串,包含以下序列 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.