Table of Contents
pack
What is byte order?
High/low byte
High/low address
Big endian (network byte order)
Host word Chapter sequence
a and A (packed string, filled with NUL or spaces)
h and H
c and C
Integer related
f and d
x, X, Z, @
unpack
What are the uses of these two functions
Home Backend Development PHP Tutorial How to use pack and unpack in PHP

How to use pack and unpack in PHP

Mar 26, 2018 pm 02:30 PM
Instructions

There are two functions pack and unpack in PHP. Many PHPers have never used them in actual projects, and they don’t even know what these two methods are used for. This article mainly talks about how to use pack and unpack in PHP. I hope it can help you.

pack

string pack ( string $format [, mixed $args [, mixed $... ]] )
Copy after login

This function is used to pack the corresponding parameters ($args) into a binary string.

The first parameter, $format, has the following options (there are many optional parameters, and some commonly used ones will be explained later):
a Fill the string blanks with NUL bytes
A With SPACE (space) padding string
h Hexadecimal string, low digit first
H Hexadecimal string, high byte first
c Signed character
C Unsigned character
s Signed short (16 bits, host byte order)
S Unsigned short (16 bits, host byte order)
n Unsigned short (16 bits, big endian) Endianness)
v Unsigned short integer (16 bits, little endian)
i Signed integer (machine dependent big and small endian)
I Unsigned integer (machine dependent) Big and small byte order)
l Signed long integer (32 bits, host byte order)
L Unsigned long integer (32 bits, host byte order)
N Unsigned long integer (32 bits, big endian)
V Unsigned long integer (32 bits, little endian)
q Signed long integer (64 bits, host byte order)
Q Unsigned long integer type (64 bits, host byte order)
J Unsigned long integer type (64 bits, big endian byte order)
P Unsigned long integer type (64 bits , little endian byte order)
f Single precision floating point type (machine dependent size)
d Double precision floating point type (machine dependent size)
x NUL byte
X Fallback one word Section
Z Fill the string blanks with NUL bytes (new in PHP 5.5)
@ Fill NUL to the absolute position

After seeing so many parameters, I was really confused for the first time Wow, most of the instructions are easy to understand, but what is the endianness of the host, big endian, little endian, etc.? The following content is relatively boring, but it must be understood, so stick with it.

What is byte order?

就是字节的顺序,说白了就是多字节数据的存放顺序(一个字节显然不需要顺序)。
比如A和B分别对应的二进制表示为0100 0001、0100 0010。对于储存字符串AB,我们可以0100 0001 0100 0010也可以0100 0010 0100 0001,这个顺序就是所谓的字节序。
Copy after login

High/low byte

比如字符串AB,左高右低(我们正常的阅读顺序),A为高字节,B为低字节
Copy after login

High/low address

假设0x123456是按从高位到底位的顺序储存,内存中是这样存放的:

高地址 -> 低地址12 -> 34 -> 56
Copy after login

Big endian (network byte order)

大端就是将高位字节放到内存的低地址端,低位字节放到高地址端。网络传输中(比如TCP/IP)低地址端(高位字节)放在流的开始,对于2个字节的字符串(AB),传输顺序为:A(0-7bit)、B(8-15bit)。
那么小端字节序自然和大端相反。
Copy after login

Host word Chapter sequence

表示当年机器的字节序(也就是网络字节序是确定的,而主机字节序是依机器确定的),一般为小端字节序。
Copy after login

a and A (packed string, filled with NUL or spaces)

$string = pack('a6', 'china');
var_dump($string); //输出结果: string(6) "china",最后一个字节是不可见的NULecho ord($string[5]); //输出结果: 0(ASCII码中0对应的就是nul)//A同理$string = pack('A6', 'china');
var_dump($string); //输出结果: string(6) "china ",最后一个字节是空格echo ord($string[5]); //输出结果: 32(ASCII码中32对应的就是空格)
Copy after login

How to use pack and unpack in PHP
How to use pack and unpack in PHP

Bonus An ASCII table (you can use man ascii to view it under linux/unix)

h and H

$string = pack('H3', 281);
var_dump($string); //输出结果: string(2) "("for($i=0;$i<strlen($string);$i++) {echo ord($string[$i]) . PHP_EOL;
}//输出结果: 40 16
Copy after login

h and H need special explanation, they are corresponding Parameters are treated as hexadecimal characters and then packed. What does that mean? For example, the above 281 will be converted to 0x281 before packaging, because one hexadecimal digit corresponds to four binary digits. The above 0x281 is only 1.5 bytes, and will be supplemented with 0 by default to become 0x2810, the decimal corresponding to 0x28. is 40((), the decimal corresponding to 0x10 is 16 (dle invisible character), do you understand? If you don’t understand, you can leave me a message.

c and C

$string = pack(&#39;c3&#39;, 67, 68, -1);
var_dump($string); //输出:string(3) "CD�"for($i=0;$i<strlen($string);$i++) {
echo ord($string[$i]) . PHP_EOL;
}
//输出: 67 68 225
Copy after login

The final output should be 67 68 -1
ord obtains the ASCII code of the character (range 0-255). At this time, the character corresponding to -1 (0000 0001) will be output in the form of complement, which is 255 (1111 1110 + 0000 0001 = 1111 1111)

All integer types are used in exactly the same way. Just pay attention to their bit and byte order. The following uses L as an example to show

$string = pack(&#39;L&#39;, 123456789);
var_dump($string); //输出:string(4) "�["for($i=0;$i<strlen($string);$i++) {
echo ord($string[$i]) . PHP_EOL;
}
//输出: 21 205 91 7
Copy after login

f and d

$string = pack(&#39;f&#39;, 12345.123);
var_dump($string);//输出:string(4) "~�@F"var_dump(unpack(&#39;f&#39;, $string)); //这里提前用到了unpack,后面会讲解
//输出:float(12345.123046875)
Copy after login

f and d are for floating-point number packaging. As for why it is 12345.123 before packaging and 12345.123046875 after unpacking, this has something to do with the storage of floating-point numbers

x, X, Z, @

$string = pack(&#39;x&#39;); //打包一个nul字符串echo ord($string); //输出: 0
Copy after login

Regarding

$string = pack(&#39;Z2&#39;, &#39;abc5&#39;); //其实就是将从Z后面的数字位置开始,全部设置为nul
var_dump($string); //输出:string(2) "a"for($i=0;$i<strlen($string);$i++) {
echo ord($string[$i]) . PHP_EOL;
}
//输出: 97 0
Copy after login
$string = pack(&#39;@4&#39;); //我理解为填充N个nulvar_dump($string); //输出: string(4) ""for($i=0;$i<strlen($string);$i++) {echo ord($string[$i]) . PHP_EOL;
}//输出: 0 0 0 0
Copy after login

unpack

array unpack ( string $format , string $data )
Copy after login

The use of unpack is quite simple. It just talks about unpacking the data packed by pack. What parameters are used when packaging are used to unpack. I am too lazy to explain the specific use. , list a few small examples

$string = pack(&#39;L4&#39;, 1, 2, 3, 4);
var_dump(unpack(&#39;L4&#39;, $string));//输出:array(4) {
[1]=>
int(1)
[2]=>
int(2)
[3]=>
int(3)
[4]=>
int(4)
}$string = pack(&#39;L4&#39;, 1, 2, 3, 4);
var_dump(unpack(&#39;Ll1/Ll2/Ll3/Ll4&#39;, $string)); //可以指定key,用/分割//输出:array(4) {
["l1"]=>
int(1)
["l2"]=>
int(2)
["l3"]=>
int(3)
["l4"]=>
int(4)
}
Copy after login

What are the uses of these two functions

Data communication (communication with other languages ​​through binary format)
Data encryption (if you don’t tell the third party your packaging method, it will be relatively difficult for the other party to unpack it)
Save space (for example, storing relatively large numbers as strings will waste a lot of space, and only 4 digits

Related recommendations:

Detailed explanation of the use of pack and unpack

The above is the detailed content of How to use pack and unpack in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use DirectX repair tool? Detailed usage of DirectX repair tool How to use DirectX repair tool? Detailed usage of DirectX repair tool Mar 15, 2024 am 08:31 AM

The DirectX repair tool is a professional system tool. Its main function is to detect the DirectX status of the current system. If an abnormality is found, it can be repaired directly. There may be many users who don’t know how to use the DirectX repair tool. Let’s take a look at the detailed tutorial below. 1. Use repair tool software to perform repair detection. 2. If it prompts that there is an abnormal problem in the C++ component after the repair is completed, please click the Cancel button, and then click the Tools menu bar. 3. Click the Options button, select the extension, and click the Start Extension button. 4. After the expansion is completed, re-detect and repair it. 5. If the problem is still not solved after the repair tool operation is completed, you can try to uninstall and reinstall the program that reported the error.

Introduction to HTTP 525 status code: explore its definition and application Introduction to HTTP 525 status code: explore its definition and application Feb 18, 2024 pm 10:12 PM

Introduction to HTTP 525 status code: Understand its definition and usage HTTP (HypertextTransferProtocol) 525 status code means that an error occurred on the server during the SSL handshake, resulting in the inability to establish a secure connection. The server returns this status code when an error occurs during the Transport Layer Security (TLS) handshake. This status code falls into the server error category and usually indicates a server configuration or setup problem. When the client tries to connect to the server via HTTPS, the server has no

How to use Baidu Netdisk-How to use Baidu Netdisk How to use Baidu Netdisk-How to use Baidu Netdisk Mar 04, 2024 pm 09:28 PM

Many friends still don’t know how to use Baidu Netdisk, so the editor will explain how to use Baidu Netdisk below. If you are in need, hurry up and take a look. I believe it will be helpful to everyone. Step 1: Log in directly after installing Baidu Netdisk (as shown in the picture); Step 2: Then select "My Sharing" and "Transfer List" according to the page prompts (as shown in the picture); Step 3: In "Friend Sharing", you can share pictures and files directly with friends (as shown in the picture); Step 4: Then select "Share" and then select computer files or network disk files (as shown in the picture); Fifth Step 1: Then you can find friends (as shown in the picture); Step 6: You can also find the functions you need in the "Function Treasure Box" (as shown in the picture). The above is the editor’s opinion

How to correctly use the win10 command prompt for automatic repair operations How to correctly use the win10 command prompt for automatic repair operations Dec 30, 2023 pm 03:17 PM

The longer the computer is used, the more likely it is to malfunction. At this time, friends need to use their own methods to repair it. So what is the easiest way to do it? Today I will bring you a tutorial on how to repair using the command prompt. How to use win10 automatic repair command prompt: 1. Press "Win+R" and enter cmd to open the "command prompt" 2. Enter chkdsk to view the repair command 3. If you need to view other places, you can also add other partitions such as "d" 4. Enter the execution command chkdskd:/F. 5. If it is occupied during the modification process, you can enter Y to continue.

Learn to copy and paste quickly Learn to copy and paste quickly Feb 18, 2024 pm 03:25 PM

How to use the copy-paste shortcut keys Copy-paste is an operation we often encounter when using computers every day. In order to improve work efficiency, it is very important to master the copy and paste shortcut keys. This article will introduce some commonly used copy and paste shortcut keys to help readers perform copy and paste operations more conveniently. Copy shortcut key: Ctrl+CCtrl+C is the shortcut key for copying. By holding down the Ctrl key and then pressing the C key, you can copy the selected text, files, pictures, etc. to the clipboard. To use this shortcut key,

What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? What is the KMS activation tool? How to use the KMS activation tool? How to use KMS activation tool? Mar 18, 2024 am 11:07 AM

The KMS Activation Tool is a software tool used to activate Microsoft Windows and Office products. KMS is the abbreviation of KeyManagementService, which is key management service. The KMS activation tool simulates the functions of the KMS server so that the computer can connect to the virtual KMS server to activate Windows and Office products. The KMS activation tool is small in size and powerful in function. It can be permanently activated with one click. It can activate any version of the window system and any version of Office software without being connected to the Internet. It is currently the most successful and frequently updated Windows activation tool. Today I will introduce it Let me introduce to you the kms activation work

How to merge cells using shortcut keys How to merge cells using shortcut keys Feb 26, 2024 am 10:27 AM

How to use the shortcut keys for merging cells In daily work, we often need to edit and format tables. Merging cells is a common operation that can merge multiple adjacent cells into one cell to improve the beauty of the table and the information display effect. In mainstream spreadsheet software such as Microsoft Excel and Google Sheets, the operation of merging cells is very simple and can be achieved through shortcut keys. The following will introduce the shortcut key usage for merging cells in these two software. exist

How to use potplayer-How to use potplayer How to use potplayer-How to use potplayer Mar 04, 2024 pm 06:10 PM

Potplayer is a very powerful media player, but many friends still don’t know how to use potplayer. Today I will introduce how to use potplayer in detail, hoping to help everyone. 1. PotPlayer shortcut keys. The default common shortcut keys for PotPlayer player are as follows: (1) Play/pause: space (2) Volume: mouse wheel, up and down arrow keys (3) forward/backward: left and right arrow keys (4) bookmark: P- Add bookmarks, H-view bookmarks (5) full screen/restore: Enter (6) multiple speeds: C-accelerate, 7) Previous/next frame: D/

See all articles