Home > Article > Backend Development > How to convert hexadecimal to ascii code in php
php method to convert hexadecimal numbers into ascii codes: 1. Convert hexadecimal numbers into ASCII characters through the bex2bin function; 2. Convert hexadecimal numbers into ASCII characters through the pack function .
The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer
How to convert hexadecimal in php for ascii code?
Convert hexadecimal numbers to ASCII characters
Convert hexadecimal numbers to ASCII characters in php using the hex2bin function, in php5 There is no bex2bin function in. At this time, we can use the pack function to convert hexadecimal numbers into ASCII characters.
The bex2bin function syntax is as follows:
hex2bin(string)
The parameter string is the hexadecimal number that needs to be converted. The syntax of
pack function is as follows:
pack(format,args+)
Parameter description:
format: required. It specifies the format used when packaging data. Optional parameter values are as follows :
a - NUL 填充的字符串 A - SPACE 填充的字符串 h - 十六进制字符串,低位在前 H - 十六进制字符串,高位在前 c - signed char C - unsigned char s - signed short(总是16位, machine 字节顺序) S - unsigned short(总是16位, machine 字节顺序) n - unsigned short(总是16位, big endian 字节顺序) v - unsigned short(总是16位, little endian 字节顺序) i - signed integer(取决于machine的大小和字节顺序) I - unsigned integer(取决于machine的大小和字节顺序) l - signed long(总是32位, machine 字节顺序) L - unsigned long(总是32位, machine 字节顺序) N - unsigned long(总是32位, big endian 字节顺序) V - unsigned long(总是32位, little endian 字节顺序) f - float(取决于 machine 的大小和表示) d - double(取决于 machine 的大小和表示) x - NUL 字节 X - 备份一个字节 Z - NUL 填充的字符串 @ - NUL 填充绝对位置
args: Optional, specifying one or more parameters to be packed
bex2bin function converts hexadecimal numbers into ASCII characters. Examples are as follows
$str = '49206c6f7665e4b8ade59bbd'; $str = hex2bin($str); echo $str;
The output result is as follows:
I love中国
But when executing the hex2bin function, the following error may be reported:
hex2bin(): Hexadecimal input string must have an even length
There may be two reasons for the above error:
1: We There may be characters that are not hexadecimal in the hexadecimal number
2: The character length of the hexadecimal number is an odd number
So we can write like this:
$str = '49206c6f7665e4b8ade59bbd'; $str = @hex2bin($str); if ($str) { echo $str; } else { echo 0; }
The example of the pack function to convert hexadecimal numbers into ASCII characters is as follows:
$str = '49206c6f7665e4b8ade59bbd'; $str = pack("H*", $str); echo $str;
As above, this is the first step to convert hexadecimal numbers into ASCII characters
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to convert hexadecimal to ascii code in php. For more information, please follow other related articles on the PHP Chinese website!