In PHP, processing binary data and converting it into decimal is a common requirement, especially in underlying data processing and network programming. This article will introduce how to combine the bindec() function and the sprintf() function to implement the conversion of binary strings to decimal numbers, and format the output results.
bindec() is a PHP built-in function that converts binary strings into corresponding decimal numbers. Its syntax is simple:
int bindec ( string $binary_string )
For example:
$binary = "1101"; // Binary string
$decimal = bindec($binary);
echo $decimal; // Output13
bindec() only accepts strings composed of 0 and 1 , otherwise it will return 0.
sprintf() is used to format string output. It can format data into a specified format, such as the width of a specified number, padding characters, decimal digits, etc. Its typical usage is:
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
Example:
$num = 42;
echo sprintf("%05d", $num); // Output "00042",use0Fill to width5
Suppose there is a binary string, we need to convert it to decimal first, then format it into a fixed-width number, and even add a thousandth separator.
$binary = "101101"; // Binary string
// Convert to decimal first
$decimal = bindec($binary);
// 使use sprintf format,假设Output宽度为6,Zero before
$formatted = sprintf("%06d", $decimal);
echo $formatted; // Output "000045"
If you want to separate thousands of digits with commas, you can combine number_format() :
$binary = "111111111"; // 9indivual1,Decimal is511
$decimal = bindec($binary);
$formatted = number_format($decimal);
echo $formatted; // Output "511"
Suppose there is a URL that passes in binary parameter bin , we want to take out and format the output:
// ExampleURL:http://m66.net/example.php?bin=10110
$binary = $_GET['bin'] ?? '0';
$decimal = bindec($binary);
$formatted = sprintf("%08d", $decimal);
echo "Binary: $binary<br>";
echo "format后的十进制: $formatted";
Here, convert the binary string into decimal and format it into an 8-digit number, with zeros added before it.
bindec() is used to convert binary to decimal.
sprintf() can format digital output.
Combining the two can easily convert binary data and beautify output.
It can also be used with number_format() to achieve more friendly digital display.
This is very useful for handling underlying data, log display, and parameter delivery.