目錄
What Do pack() and unpack() Actually Do?
Understanding the Format Codes
Practical Example: Reading a BMP File Header
Packing Data: Building a Binary Message
Tips and Gotchas
When Should You Use These Functions?
首頁 後端開發 php教程 解開二進制數據:PHP的' PACK()”和' unvack()”的實用指南````''

解開二進制數據:PHP的' PACK()”和' unvack()”的實用指南````''

Jul 25, 2025 pm 05:59 PM
PHP Strings

PHP的pack()和unpack()函數用於在PHP變量與二進制數據之間轉換。 1. pack()將變量如整數、字符串打包成二進制數據,unpack()則將二進制數據解包為PHP變量,二者均依賴格式字符串指定轉換規則。 2. 常見格式碼包括C/c(8位有/無符號字符)、S/s(16位短整型)、L/l/V/N(32位長整型,分別對應不同字節序)、f/d(浮點/雙精度)、a/A(填充字符串)、x(空字節)等。 3. 字節序至關重要:V表示小端序(Intel),N表示大端序(網絡標準),跨平台通信時應優先使用V或N以確保一致性。 4. 實際應用中,unpack()可解析BMP文件頭,如unpack('C2signature/Vsize/Vreserved/Voffset', $binary)讀取14字節BMP頭並命名字段;pack()可用於構建自定義二進制協議,如pack('Cv', $type, $length)生成消息頭。 5. 注意事項包括:確認數據的字節序、區分有無符號類型、正確處理字符串填充方式(a用NULL填充,A用空格),並通過/name語法命名字段以提高可讀性。 6. 這些函數適用於解析ZIP、PNG等二進製文件格式,與硬件通信,實現網絡協議或處理C結構體數據,在無需擴展的情況下提供對底層數據的精細控制,只要格式字符串準確匹配數據結構,即可可靠地進行二進制數據操作。

Unpacking Binary Data: A Practical Guide to PHP\'s `pack()` and `unpack()`

Working with binary data in PHP might sound like something only low-level systems programmers deal with, but it's actually useful in many practical scenarios—like parsing file formats (PNG, ZIP), handling network protocols, or communicating with hardware. PHP's pack() and unpack() functions are powerful tools for converting between data types and their binary representations.

Unpacking Binary Data: A Practical Guide to PHP's `pack()` and `unpack()`

Let's break down how they work and when to use them—without the jargon overload.


What Do pack() and unpack() Actually Do?

At their core:

Unpacking Binary Data: A Practical Guide to PHP's `pack()` and `unpack()`
  • pack() converts PHP variables (like integers, strings) into binary data based on a format string.
  • unpack() reads binary data and converts it back into PHP variables, again using a format string.

They're like translators between PHP's high-level world and the raw bytes that computers and networks speak.

 $data = pack('S', 258); // Convert integer 258 to 2-byte unsigned short
$unpacked = unpack('S', $data); // Convert back
var_dump($unpacked); // [1] => 258

Note: unpack() returns an array, even for a single value.

Unpacking Binary Data: A Practical Guide to PHP's `pack()` and `unpack()`

Understanding the Format Codes

The magic (and confusion) lies in the format string —a sequence of letters and numbers telling PHP how to interpret the data.

Here are the most commonly used codes:

Code Meaning Size (bytes)
C Unsigned char (8-bit) 1
c Signed char 1
S Unsigned short (16-bit, LE) 2
s Signed short 2
L Unsigned long (32-bit, LE) 4
l Signed long 4
N Unsigned long (32-bit, BE) 4
V Unsigned long (32-bit, LE) 4
f Float (32-bit) 4
d Double (64-bit) 8
a NUL-padded string configurable
A Space-padded string configurable
x NUL byte (skip) 1

Note on endianness :

  • V = Little-endian (Intel, most common)
  • N = Big-endian (network byte order)
  • L = Machine-dependent (usually little-endian)

If you're dealing with cross-platform or network data, prefer N and V for predictable behavior.


Practical Example: Reading a BMP File Header

Let's say you want to read basic info from a BMP file. The first 14 bytes are the file header.

 $file = fopen('image.bmp', 'rb');
$binary = fread($file, 14);
fclose($file);

// Unpack BMP header
$header = unpack('C2signature/Vsize/Vreserved/Voffset', $binary);

// Result:
// $header['signature1'] = 66 ('B')
// $header['signature2'] = 77 ('M')
// $header['size'] = file size in bytes
// $header['offset'] = where pixel data starts

Here:

  • C2signature reads two bytes as unsigned chars and names them signature1 , signature2
  • Vsize reads a 32-bit unsigned long in little-endian (BMP uses little-endian)
  • You can name fields by adding /name after the format code

This makes it easy to parse structured binary formats.


Packing Data: Building a Binary Message

Imagine you're creating a simple binary protocol where each message contains:

  • Message type (1 byte)
  • Length (2 bytes, little-endian)
  • Payload (string)
 $messageType = 1;
$payload = 'Hello';
$length = strlen($payload);

$binary = pack('Cv', $messageType, $length) . $payload;

Here:

  • C = message type (unsigned char)
  • v = length as unsigned short, little-endian (lowercase = little-endian)

Now $binary can be sent over a socket or saved to a file.

To read it back:

 $data = unpack('Ctype/vlength', $binary);
$payload = substr($binary, 3, $data['length']);

Tips and Gotchas

  • Endianness matters : When working with hardware or network protocols, always confirm byte order. Use N (big-endian) or V (little-endian) for consistency.
  • Signed vs. unsigned : c vs C , s vs S —mixing them up leads to negative numbers or overflow.
  • String padding : a pads with NULLs, A with spaces. Use a for binary-safe strings.
  • Field naming : Use /name syntax to make results readable:
     unpack('Cversion/Ctype/a10data', $bin);
    // returns ['version'=>1, 'type'=>2, 'data'=>"payload..."]
  • unpack() returns indexed arrays by default unless you name the fields.

  • When Should You Use These Functions?

    • Parsing binary file formats: ZIP, PNG, WAV, etc.
    • Communicating with embedded devices or sensors
    • Creating or reading custom binary protocols
    • Handling packed data from C structures or databases

    They're not everyday tools, but when you need them, there's no real alternative in pure PHP.


    Basically, pack() and unpack() give you fine-grained control over binary data without needing extensions or external libraries. It's not flashy, but once you understand the format codes, you can interface with low-level data structures directly in PHP.

    Just remember: match your format string to the data's structure and byte order—get that right, and the rest follows.

    以上是解開二進制數據:PHP的' PACK()”和' unvack()”的實用指南````''的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

PHP教程
1592
276
字符串作為價值對象:一種現代的特定領域字符串類型的方法 字符串作為價值對象:一種現代的特定領域字符串類型的方法 Aug 01, 2025 am 07:48 AM

Rawstringsindomain-drivenapplicationsshouldbereplacedwithvalueobjectstopreventbugsandimprovetypesafety;1.Usingrawstringsleadstoprimitiveobsession,whereinterchangeablestringtypescancausesubtlebugslikeargumentswapping;2.ValueobjectssuchasEmailAddressen

用零字節和PHP中的字符串終止解決常見的陷阱 用零字節和PHP中的字符串終止解決常見的陷阱 Jul 28, 2025 am 04:42 AM

nullbytes(\ 0)cancauseunexpectedBehaviorInphpWhenInterfacingWithCextensOsSySycallsBecaUsectReats \ 0asastringTermInator,EventHoughPhpStringSareBinary-SaftringsareBinary-SafeanDeandSafeanDeandPresserve.2.infileperations.2.infileperations,filenamecontakecontakecontablescontakecontabternallikebybybytartslikeplikebybytrikeplinebybytrikeplike'''''''';

帶有' sprintf”和' vsprintf”的高級字符串格式化技術 帶有' sprintf”和' vsprintf”的高級字符串格式化技術 Jul 27, 2025 am 04:29 AM

sprintf和vsprintf在PHP中提供高級字符串格式化功能,答案依次為:1.可通過%.2f控制浮點數精度、%d確保整數類型,並用d實現零填充;2.使用%1$s、%2$d等positional佔位符可固定變量位置,便於國際化;3.通過%-10s實現左對齊、]右對齊,適用於表格或日誌輸出;4.vsprintf支持數組傳參,便於動態生成SQL或消息模板;5.雖無原生命名佔位符,但可通過正則回調函數模擬{name}語法,或結合extract()使用關聯數組;6.應通過substr_co

與PHP的PCRE功能相匹配的高級模式 與PHP的PCRE功能相匹配的高級模式 Jul 28, 2025 am 04:41 AM

PHP的PCRE函數支持高級正則功能,1.使用捕獲組()和非捕獲組(?:)分離匹配內容並提升性能;2.利用正/負向先行斷言(?=)和(?!))及後發斷言(?

解開二進制數據:PHP的' PACK()”和' unvack()”的實用指南````'' 解開二進制數據:PHP的' PACK()”和' unvack()”的實用指南````'' Jul 25, 2025 pm 05:59 PM

PHP的pack()和unpack()函數用於在PHP變量與二進制數據之間轉換。 1.pack()將變量如整數、字符串打包成二進制數據,unpack()則將二進制數據解包為PHP變量,二者均依賴格式字符串指定轉換規則。 2.常見格式碼包括C/c(8位有/無符號字符)、S/s(16位短整型)、L/l/V/N(32位長整型,分別對應不同字節序)、f/d(浮點/雙精度)、a/A(填充字符串)、x(空字節)等。 3.字節序至關重要:V表示小端序(Intel),N表示大端序(網絡標準),跨平台通信時應優先使用V

防禦弦處理:防止XSS和PHP注射攻擊 防禦弦處理:防止XSS和PHP注射攻擊 Jul 25, 2025 pm 06:03 PM

TodefendagainstXSSandinjectioninPHP:1.Alwaysescapeoutputusinghtmlspecialchars()forHTML,json_encode()forJavaScript,andurlencode()forURLs,dependingoncontext.2.Validateandsanitizeinputearlyusingfilter_var()withappropriatefilters,applywhitelistvalidation

導航PHP字符串編碼的迷宮:UTF-8及以後 導航PHP字符串編碼的迷宮:UTF-8及以後 Jul 26, 2025 am 09:44 AM

UTF-8處理在PHP中需手動管理,因PHP默認不支持Unicode;1.使用mbstring擴展提供多字節安全函數如mb_strlen、mb_substr並顯式指定UTF-8編碼;2.確保數據庫連接使用utf8mb4字符集;3.通過HTTP頭和HTML元標籤聲明UTF-8;4.文件讀寫時驗證並轉換編碼;5.JSON處理前確保數據為UTF-8;6.利用mb_detect_encoding和iconv進行編碼檢測與轉換;7.預防數據損壞優於事後修復,需在所有層級強制使用UTF-8以避免亂碼問題。

超越JSON:了解PHP的本地字符串序列化 超越JSON:了解PHP的本地字符串序列化 Jul 25, 2025 pm 05:58 PM

PHP的原生序列化比JSON更適合PHP內部數據存儲與傳輸,1.因為它能保留完整數據類型(如int、float、bool等);2.支持私有和受保護的對象屬性;3.可安全處理遞歸引用;4.反序列化時無需手動類型轉換;5.在性能上通常優於JSON;但不應在跨語言場景使用,且絕不能對不可信輸入調用unserialize(),以免引發遠程代碼執行攻擊,推薦在僅限PHP環境且需高保真數據時使用。

See all articles