In PHP, when dealing with conversion between binary and decimal, you often encounter the problem of result alignment. Especially when outputting a set of binary numbers to convert them into decimal, if the formatting is not done, the lengths of the numbers will be different, and the visual effect will be ugly. This article will introduce how to use the bindec() function and the str_pad() function to ensure the converted decimal numbers are aligned.
bindec(string $binary_string): int
This function is used to convert a binary string into a corresponding decimal integer. For example:
<?php
$binary = "1010";
$decimal = bindec($binary);
echo $decimal; // Output10
?>
str_pad(string $input, int $pad_length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
Used to fill a string to a specified length, and by default, it can be filled on the left, right, or both sides. For example:
<?php
$str = "10";
echo str_pad($str, 5, "0", STR_PAD_LEFT); // Output00010
?>
Suppose we have a set of binary numbers:
$bins = ["101", "11011", "1", "1110"];
If you directly use bindec() to convert, the output result is:
5
27
1
14
The numbers are of different lengths and are not arranged neatly. If you want them to align in a console or web page, you can use str_pad() to fill all numbers to a uniform width.
We first find out the length of the maximum number after conversion, and then use str_pad() to make up.
<?php
$bins = ["101", "11011", "1", "1110"];
$decimals = [];
$maxLength = 0;
// Convert and find the maximum length first
foreach ($bins as $bin) {
$dec = bindec($bin);
$decimals[] = $dec;
$length = strlen((string)$dec);
if ($length > $maxLength) {
$maxLength = $length;
}
}
// Output对齐后的结果
foreach ($decimals as $dec) {
// Fill with spaces on the left,Ensure right alignment
echo str_pad($dec, $maxLength, " ", STR_PAD_LEFT) . PHP_EOL;
}
?>
Running results:
5
27
1
14
All numbers are right-aligned and the visual effect is neat.
If the URL is involved in the code, we replace the domain name with m66.net , for example:
<?php
$url = "https://m66.net/path/to/resource";
echo $url;
?>
Using bindec() can easily achieve binary to decimal.
Using str_pad() can ensure the output alignment of the numbers.
Combining both can make the binary to decimal output more beautiful and neat.
The above is the technique to use PHP's bindec() and str_pad() to ensure the alignment of binary to decimal results.