目录

PHP unpack() 函数

❮ PHP 其他参考

示例

从二进制字符串中解包数据:

<?php
$data = "PHP";
print_r(unpack("C*",$data));
?>
亲自试一试 »

定义和用法

unpack() 函数从二进制字符串中解包数据。


语法

unpack(format,data)

参数值

Parameter Description
format Required. Specifies the format to use when unpacking data.

Possible values:

  • a - NUL-padded string
  • A - SPACE-padded string
  • h - Hex string, low nibble first
  • H - Hex string, high nibble first
  • c - signed char
  • C - unsigned 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)
  • N - unsigned long (always 32 bit, big endian byte order)
  • V - unsigned long (always 32 bit, little endian byte order)
  • q - signed long long (always 64 bit, machine byte order)
  • Q - unsigned long long (always 64 bit, machine byte order)
  • J - unsigned long long (always 64 bit, big endian byte order)
  • P - unsigned long long (always 64 bit, little endian byte order)
  • f - float (machine dependent size and representation)
  • g - float (machine dependent size, little endian byte order)
  • G - float (machine dependent size, big endian byte order)
  • d - double (machine dependent size and representation)
  • e - double (machine dependent size, little endian byte order)
  • E - double (machine dependent size, big endian byte order)
  • x - NUL byte
  • X - Back up one byte
  • Z - NUL-padded string
  • @ - NUL-fill to absolute
data Required. Specifies the binary data to be unpacked
offset Optional. Specifies where to start unpacking from. Default is 0.


技术细节

返回值: 成功时返回一个数组,失败时返回 FALSE。
PHP 版本: 4+
变更日志: PHP 7.2 - float 和 double 现在支持大端和小端。
PHP 7.1 - 添加了可选的偏移参数。
PHP 5.5.0 - 为了 Perl 兼容性进行了以下更改: "a" 代码现在保留尾随 NULL 字节。
"A" 代码现在会去除所有尾随 ASCII 空格。
添加了 "Z" 代码用于 NULL 填充字符串,并删除尾随 NULL 字节。

更多示例

示例

解压数据:

<?php
$data = "PHP";
print_r(unpack("C*myint",$data));
?>
亲自试一试 »

示例

解压数据:

<?php
$bin = pack("c2n2",0x1234,0x5678,65,66);
print_r(unpack("c2chars/n2int",$bin));
?>
亲自试一试 »

❮ PHP 其他参考