PHP bin2hex()和pack()函数的转换
bin2hex() 和 pack() 函数
定义和用法 pack() 函数把数据装入一个二进制字符串。 语法 pack(format,args+)
参数 描述 format 必需。规定在包装数据时所使用的格式。 args+ 可选。规定被包装的一个或多个参数。
format 参数的可能值: a - NUL-padded string A - SPACE-padded string h - Hex string, low nibble first H - Hex string, high nibble first c - signed char C - unsigned char s - signed short (always 16 bit, machine byte order) S - unsigned short (always 16 bit, machine byte order) n - unsigned short (always 16 bit, big endian byte order) v - unsigned short (always 16 bit, little endian byte order) i - signed integer (machine dependent size and byte order) I - unsigned integer (machine dependent size and byte order) l - signed long (always 32 bit, machine byte order) L - unsigned long (always 32 bit, machine byte order) N - unsigned long (always 32 bit, big endian byte order) V - unsigned long (always 32 bit, little endian byte order) f - float (machine dependent size and representation) d - double (machine dependent size and representation) x - NUL byte X - Back up one byte @ - NUL-fill to absolute position
定义和用法 bin2hex() 函数把 ASCII 字符的字符串转换为十六进制值。字符串可通过使用 pack() 函数再转换回去。
语法 bin2hex(string) 参数 描述 string 必需。要转换的字符串。
技术细节 返回值: 返回要转换字符串的十六进制值。 PHP 版本: 4+
$result = bin2hex($str)的作用是将$str字符串变量的ASCII码值(即二进制形式)转换为十六进制形式
要将最终结果转换回来,方法是pack("H*",$result);
-
例子:将把一个字符串值从二进制转换为十六进制,再转换回去:
$str = "Hello world!";echo bin2hex($str);echo pack("H*",bin2hex($str));
输出:
48656c6c6f20776f726c6421Hello world!
-
当然用这个bin2hex()还可以把图片转换为十六进制形式字符串 和 图片的十六进制形式字符串 转图片。
$file="test.jpg"; $data=file_get_contents($file); $newdata=bin2hex($data); echo $newdata;
$data=pack('H*',$newdata);
echo $data;
浙公网安备 33010602011771号