我们发现,如果使用echo或者print输出一个十六进制数,输出的结果会自动转换成十进制,例如
$hex = 0x3e24; echo $hex; print $hex;
这样会直接输出
我们使用进制转换工具可以知道3e24的十进制为15908
我们先来看看sprintf函数的用法,其中的format参数有提到x跟X格式的使用效果,x就是以小写十六进制输出内容,X则是以大写十六进制输出内容
sprintf
(PHP 4, PHP 5, PHP 7)
sprintf — Return a formatted string
说明
string sprintf ( string $format
[, mixed $args
[, mixed $...
]] )
Returns a string produced according to the formatting string format
.
参数
format
x - the argument is treated as an integer
and presented as a hexadecimal number (with lowercase letters).
X - the argument is treated as an integer
and presented as a hexadecimal number (with uppercase letters).
不过sprintf只是返回一串格式化后的字符串,并没有把它输出来,所有要结合echo使用,示例:
$hex = 0x3e24; echo sprintf('这是一个十六进制数:%x', $hex);
输出结果为:这是一个十六进制数:3e24
当然我们可以使用printf更加简便地输出十六进制
printf
(PHP 4, PHP 5, PHP 7)
printf — 输出格式化字符串
说明
int printf ( string $format
[, mixed $args
[, mixed $...
]] )
依据 format
格式参数产生输出。
参数
format
format
描述信息,请参见 sprintf()。args
简化后的代码就是:
$hex = 0x3e24; printf('这是一个十六进制数:%x', $hex);
附注:
% - a literal percent character. No
argument is required.
b - the argument is treated as an
integer, and presented as a binary number.
c - the argument is treated as an
integer, and presented as the character with that ASCII value.
d - the argument is treated as an
integer, and presented as a (signed) decimal number.
e - the argument is treated as scientific
notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
E - like %e but uses uppercase letter (e.g. 1.2E+2).
f - the argument is treated as a float, and presented as a floating-point number (locale aware).
F - the argument is treated as a float, and presented as a floating-point number (non-locale aware). Available since PHP 5.0.3.
g - shorter of %e and %f.
G - shorter of %E and %f.
o - the argument is treated as an integer, and presented as an octal number.
s - the argument is treated as and presented as a string.
u - the argument is treated as an integer, and presented as an unsigned decimal number.
Type | Specifiers |
---|---|
string | s |
integer | d, u, c, o, x, X, b |
double | g, G, e, E, f, F |
来自ansion
2017-3-21