Current Location: Home> Latest Articles> How to Perform Bit-Level Operations on Binary Strings in PHP Using bindec() and substr()

How to Perform Bit-Level Operations on Binary Strings in PHP Using bindec() and substr()

M66 2025-06-12

When working with binary strings in PHP, it's common to encounter situations where you need to extract or modify certain bits. The bindec() function converts a binary string to a decimal integer, while the substr() function allows us to extract a part of a string. By combining both functions, bit-level operations on binary strings can be easily achieved.

Overview of bindec() and substr()

  • 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 a string. For example, substr('101101', 2, 3) returns '110'.

Example: Extract Specific Bits from a Binary String and Convert to Decimal

Suppose you have a binary string and you want to extract 4 bits starting from the 3rd position and then convert them to decimal.

<?php
$binaryString = "1101011011"; // Original binary string
<p>// Use substr to extract 4 bits starting from index 2 (indexing starts at 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 "Corresponding decimal value: " . $decimalValue . "\n"; // Output: 5<br>
?><br>

Explanation of Example

  • substr($binaryString, 2, 4): Extracts 4 bits starting from the 3rd character of the original string (indexing starts at 0), resulting in "0101".

  • bindec("0101"): Converts "0101" to decimal 5.

Advanced: Modify a Specific Bit in a Binary String

In addition to extraction, you can also modify a specific bit in a binary string:

<?php
$binaryString = "1101011011";
<p>// Set 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>

Summary

By combining substr() for extracting parts of a string and bindec() for conversion, you can easily perform bit-level extraction and conversion on binary strings. With additional string manipulation functions, even more complex binary data processing can be achieved.