小码哥的IT人生

首页 > PHP > php基础

PHP unpack() 函数 详解

php基础 2022-06-07 17:12:19小码哥的IT人生shichen

PHP unpack() 函数

定义和用法

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

语法

unpack(format,data)
参数 描述
format 必需。规定在解包数据时所使用的格式。
data 可选。规定被解包的二进制数据。

format 参数的可能值:

  1. a - NUL-padded string
  2. A - SPACE-padded string
  3. h - Hex string, low nibble first
  4. H - Hex string, high nibble first
  5. c - signed char
  6. C - unsigned char
  7. s - signed short (always 16 bit, machine byte order)
  8. S - unsigned short (always 16 bit, machine byte order)
  9. n - unsigned short (always 16 bit, big endian byte order)
  10. v - unsigned short (always 16 bit, little endian byte order)
  11. i - signed integer (machine dependent size and byte order)
  12. I - unsigned integer (machine dependent size and byte order)
  13. l - signed long (always 32 bit, machine byte order)
  14. L - unsigned long (always 32 bit, machine byte order)
  15. N - unsigned long (always 32 bit, big endian byte order)
  16. V - unsigned long (always 32 bit, little endian byte order)
  17. f - float (machine dependent size and representation)
  18. d - double (machine dependent size and representation)
  19. x - NUL byte
  20. X - Back up one byte
  21. @ - NUL-fill to absolute position

实例

例子 1

<?php
$data = "PHP";
print_r(unpack("C*",$data));
?>

输出:

Array
(
[1] => 80
[2] => 72
[3] => 80
)

例子 2

<?php
$data = "PHP";
print_r(unpack("C*myint",$data));
?>

输出:

Array
(
[myint1] => 80
[myint2] => 72
[myint3] => 80
)

例子 3

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

输出:

Array
(
[chars1] => 52
[chars2] => 120
[int1] => 65
[int2] => 66
)

版权所有 © 小码哥的IT人生
Copyright © phpcodeweb All Rights Reserved
ICP备案号:苏ICP备17019232号-2  

苏公网安备 32030202000762号

© 2021-2024