Current Location: Home> Latest Articles> How to Use PHP's bindec() Function with substr() for Bit-Level Operations on Binary Strings

How to Use PHP's bindec() Function with substr() for Bit-Level Operations on Binary Strings

gitbox 2025-06-12

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.

Introduction to 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 the string. For example: substr('101101', 2, 3) returns '110'.

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

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>

Explanation of Example

  • 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.

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>// 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>

Summary

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.