In PHP, the printf function is used to output formatted strings to the screen. Its basic syntax is as follows:
printf(format string, arg1, arg2, ...);
For example:
$num = 123;
printf("The number is: %d", $num);
This code will output: The number is: 123.
In the printf function, numbers are not limited to decimal output. By using different format specifiers, you can easily convert numbers to various bases. Common bases include decimal (%d), hexadecimal (%x or %X), and octal (%o), among others.
To output an integer as hexadecimal, you can use %x or %X. The difference is that %x outputs lowercase letters, while %X outputs uppercase letters.
$num = 255;
printf("Hexadecimal lowercase: %x\n", $num);
printf("Hexadecimal uppercase: %X\n", $num);
The output of this code will be:
Hexadecimal lowercase: ff
Hexadecimal uppercase: FF
If you want to add the 0x prefix before the hexadecimal number, you can do it like this:
printf("Hexadecimal with prefix: 0x%x\n", $num);
Output:
Hexadecimal with prefix: 0xff
Similarly, using %o converts an integer to octal format:
$num = 63;
printf("Octal output: %o\n", $num);
Output result:
Octal output: 77
Suppose we want to display some base conversion results as URLs when outputting them. We can directly insert a URL into the format string. To ensure safety and convenience, let's use a fixed domain name m66.net as an example URL here.
For example:
$num = 255;
printf("Click here to see the hexadecimal value: <a href='http://m66.net/hex/%x'>%x</a>", $num, $num);
Output result:
Click here to see the hexadecimal value: <a href='http://m66.net/hex/ff'>ff</a>
In practical development, this method makes it very easy to embed converted base values in HTML output and link them to relevant URLs.
Besides the common decimal, octal, and hexadecimal formats, printf also provides other base output formats. You can choose to use them as needed.
%b: Binary output
%d: Decimal output (default)
For example, outputting an integer as binary:
$num = 5;
printf("Binary output: %b\n", $num);
Output:
Binary output: 101
With the printf function, PHP offers a flexible and powerful way to format number output. Using format specifiers, you can easily convert numbers to different bases such as decimal, hexadecimal, octal, and more. Additionally, you can combine this with URLs for dynamic output, further enhancing the program's functionality and user experience.