When working with binary strings in PHP, there are often scenarios where you need to extract or modify specific bits. The bindec() function can convert a binary string to a decimal integer, while the substr() function helps us extract a portion of the string. By combining these two functions, we can perform bit-level operations on binary strings.
bindec(string $binary_string): int
Converts a binary string to a decimal integer. For example: bindec('101') returns 5.
substr(string $string, int $start, int $length = null): string
Extracts a substring from the string. For example: substr('101101', 2, 3) returns '110'.
Suppose you have a binary string, and you want to extract the 4 bits starting from the 3rd position, then convert them to decimal.
<?php
$binaryString = "1101011011"; // Original binary string
<p>// Use substr to extract a substring starting at index 2 with a length of 4 (note that index starts from 0)<br>
$subBinary = substr($binaryString, 2, 4); // "0101"</p>
<p>// Use bindec to convert the extracted binary string to decimal<br>
$decimalValue = bindec($subBinary);</p>
<p>echo "Binary substring: " . $subBinary . "\n"; // Output: 0101<br>
echo "Decimal value: " . $decimalValue . "\n"; // Output: 5<br>
?><br>
substr($binaryString, 2, 4): Extracts a substring starting from the 3rd character (index starts from 0) with a length of 4, resulting in "0101".
bindec("0101"): Converts "0101" to decimal 5.
In addition to extraction, you can also modify a specific bit in a binary string:
<?php
$binaryString = "1101011011";
<p>// Change the 5th bit (index 4) to 1<br>
$pos = 4;<br>
$newBit = '1';</p>
<p>// Modify the string<br>
$binaryString = substr_replace($binaryString, $newBit, $pos, 1);</p>
<p>echo "Modified binary string: " . $binaryString . "\n";<br>
?><br>
By combining substr() for extracting substrings and bindec() for conversion, you can easily perform bit-level extraction and conversion on binary strings. With other string manipulation functions, you can even perform more complex binary data processing.