bin2hex() 將二進位字串轉為十六進位字串,每個位元組對應兩個十六進位字元。常用於二進位資料儲存、傳輸、除錯顯示、雜湊值呈現等場景。
<?php
$string = "Hello\tworld!\n";
echo "原始: $string\n";
echo "Hex: " . bin2hex($string) . "\n";
// 輸出:48656c6c6f09776f726c64210a
// H e l l o \t w o r l d ! \n
// 48 65 6c 6c 6f 09 77 6f 72 6c 64 21 0a
?>
<?php
$hex = '48656c6c6f09776f726c64210a';
$binary = hex2bin($hex);
echo $binary; // Hello world!
?>
bin2hex(hash('sha256', $data, true)) 取得原始二進位雜湊再轉 Hex。bin2hex() 後可安全放入 URL 參數(僅含 0-9 a-f)。| 函數 | 用途 | 輸出長度 |
|---|---|---|
| bin2hex() | 二進位 -> Hex | 2x 原長度 |
| base64_encode() | 二進位 -> Base64 | ~1.33x 原長度 |
| pack('H*', $hex) | Hex -> 二進位 (舊版) | - |