php pack()函数详解与示例

来源:互联网 发布:王心凌honey 知乎 编辑:程序博客网 时间:2024/06/05 11:02
 

手册:

pack

(PHP 3, PHP 4, PHP 5)

pack -- Pack data into binary string

说明

string pack ( string format [, mixed args [, mixed ...]] )

Pack given arguments into binary string according to format.

The idea to this function was taken from Perl and all formatting codes work the same as there, however, there are some formatting codes that are missing such as Perl's "u" format code.

Note that the distinction between signed and unsigned values only affects the functionunpack(), where as function pack() gives the same result for signed and unsigned format codes.

Also note that PHP internally stores integer values as signed values of a machine dependent size. If you give it an unsigned integer value too large to be stored that way it is converted to afloat which often yields an undesired result.

参数

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, 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.

Currently implemented formats are:

表 1. pack() format characters

CodeDescriptionaNUL-padded stringASPACE-padded stringhHex string, low nibble firstHHex string, high nibble firstcsigned charCunsigned charssigned short (always 16 bit, machine byte order)Sunsigned short (always 16 bit, machine byte order)nunsigned short (always 16 bit, big endian byte order)vunsigned short (always 16 bit, little endian byte order)isigned integer (machine dependent size and byte order)Iunsigned integer (machine dependent size and byte order)lsigned long (always 32 bit, machine byte order)Lunsigned long (always 32 bit, machine byte order)Nunsigned long (always 32 bit, big endian byte order)Vunsigned long (always 32 bit, little endian byte order)ffloat (machine dependent size and representation)ddouble (machine dependent size and representation)xNUL byteXBack up one byte@NUL-fill to absolute position

args

返回值

Returns a binary string containing data.

翻译:

pack()函数的作用是:将数据压缩成一个二进制字符串。

  • a - NUL-padded string
    a - NUL- 字符串填满[padded string]
  • A - SPACE-padded string
    A - SPACE- 字符串填满[padded string]
  • h - Hex string, low nibble first
    h – 十六进制字符串,低“四位元”[low nibble first]
  • H - Hex string, high nibble first
    H - 十六进制字符串,高“四位元”[high nibble first]
  • c - signed char
    c – 带有符号的字符
  • C - unsigned char
    C – 不带有符号的字符
  • s - signed short (always 16 bit, machine byte order)
    s – 带有符号的短模式[short](通常是16位,按机器字节顺序)
  • S - unsigned short (always 16 bit, machine byte order)
    S – 不带有符号的短模式[short](通常是16位,按机器字节排序)
  • n - unsigned short (always 16 bit, big endian byte order)
    n -不带有符号的短模式[short](通常是16位,按大endian字节排序)
  • v - unsigned short (always 16 bit, little endian byte order)
    v -不带有符号的短模式[short](通常是16位,按小endian字节排序)
  • i - signed integer (machine dependent size and byte order)
    i – 带有符号的整数(由大小和字节顺序决定)
  • I - unsigned integer (machine dependent size and byte order)
    I – 不带有符号的整数(由大小和字节顺序决定)
  • l - signed long (always 32 bit, machine byte order)
    l– 带有符号的长模式[long](通常是32位,按机器字节顺序)
  • L - unsigned long (always 32 bit, machine byte order)
    L – 不带有符号的长模式[long](通常是32位,按机器字节顺序)
  • N - unsigned long (always 32 bit, big endian byte order)
    N – 不带有符号的长模式[long](通常是32位,按大edian字节顺序)
  • V - unsigned long (always 32 bit, little endian byte order)
    V– 不带有符号的长模式[long](通常是32位,按小edian字节顺序)
  • f - float (machine dependent size and representation)
    f –浮点(由大小和字节顺序决定)
  • d - double (machine dependent size and representation)
    d – 双精度(由大小和字节顺序决定)
  • x - NUL byte
    x – 空字节[NUL byte]
  • X - Back up one byte
    X- 后面一个字节[Back up one byte]
  • @ - NUL-fill to absolute position
    @ - NUL- 添加到一个绝对位置[absolute position]

下表是一些格式字符与C中数据类型的等价关系:

字符  等价C数据类型CcharddoubleffloatiintIunsigned int (or unsigned)llongLunsigned longsshortSunsigned short

args+  

      Optional. Specifies one or more arguments to be packed

      可选参数。指定一个或多个用于打包的自变量

实例示例:

// 调用方发过来的日志数据包
typedef struct LoggerPackage
{
    // 查询关键字
    char            keyword[ 127 ];    // 栏目(0-4 | 99)
    unsigned char   column;    // 命中次数(big endian)网络字节序
    uint32_t        hit_count;    // 8字节对齐
    char            reserved[ 4 ];
} LoggerPackage;
$sock= new CSocket();
$sock->create_tcp();
if (!$sock->connect($Server_ip, $Server_port, $gs_Search_Timeout)) {
   echo "connect failed!\n";
   exit(0);
}
//打包发包
$keywodlen=strlen($package->keyword);
//a- 用空字符(null)补足的字符串,后面的整数就是重复多少个
//c- 带符号字符(通常-128~127),对应c/c++里面的char型
//N- 网络序长整数,对应C里面的hton()
$format_str="a24a127cNa4";
$send_pack=pack($format_str,$package->header,$package->keyword,$package->column,$package->hit_count,$package->reserved);
$send_len=strlen($send_pack);

$sock->send($send_pack, strlen($send_pack), 0);

函数名unpack调用语法@list = unpack (packformat, formatstr);解说unpack与pack功能相反,将以机器格式存贮的值转化成Perl中值的列表。其格式字符与pack基本相同(即上表),不同的有:A格式将机器格式字符串转化为Perl字符串并去掉尾部所有空格或空字符;x为跳过一个字节;@为跳过一些字节到指定的位置,如@4为跳过4个字节。下面看一个@和X合同的例子:     $longrightint = unpack ("@* X4 L", $packstring);
   此语句将最后四个字节看作无符号长整数进行转化。下面看一个对uuencode文件解码的例子:
1 : #!/usr/local/bin/perl
2 :
3 : open (CODEDFILE, "/u/janedoe/codefile") ||
4 : die ("Can't open input file");
5 : open (OUTFILE, ">outfile") ||
6 : die ("Can't open output file");
7 : while ($line = <CODEDFILE>) {
8 : $decoded = unpack("u", $line);
9 : print OUTFILE ($decoded);
10: }
11: close (OUTFILE);
12: close (CODEDFILE);
   当将pack和unpack用于uuencode时,要记住,虽然它们与UNIX中的uuencode、uudecode工具算法相同,但并不提供首行和末行,如果想用uudecode对由pack的输出创建的文件进行解码,必须也把首行和末行输出(详见UNIX中uuencode帮助)。
原创粉丝点击