PHP bindec() Function

The bindec() function converts a binary number represented as a string into its decimal equivalent. The binary string is interpreted as an unsigned integer, and invalid characters (other than 0 and 1) are ignored.

Syntax

bindec(string $binary_string): int|float

Parameters

Parameter Description
binary_string A string containing binary digits (0 and 1). Invalid characters are ignored.

Return Value

Returns the decimal equivalent as an integer or float (for large numbers).

Examples

Basic Usage

Converting a simple binary string to decimal ?

<?php
    echo bindec('1111') . "<br>";        // Binary 1111 to decimal
    echo bindec('1010') . "<br>";        // Binary 1010 to decimal
    echo bindec('11111111') . "<br>";    // Binary 11111111 to decimal
?>
15
10
255

Handling Invalid Characters

The function ignores non-binary characters in the string ?

<?php
    echo bindec('1a1b0c1') . "<br>";     // Invalid chars ignored
    echo bindec('1111xyz') . "<br>";     // Invalid chars at end
    echo bindec('abc1010') . "<br>";     // Invalid chars at start
?>
101
15
10

Large Binary Numbers

For very large binary numbers, the function may return a float ?

<?php
    $largeBinary = str_repeat('1', 32);  // 32 ones
    echo "Binary: " . $largeBinary . "<br>";
    echo "Decimal: " . bindec($largeBinary) . "<br>";
    echo "Type: " . gettype(bindec($largeBinary));
?>
Binary: 11111111111111111111111111111111
Decimal: 4294967295
Type: integer

Conclusion

The bindec() function provides a simple way to convert binary strings to decimal numbers. It automatically handles invalid characters and can return either integer or float values depending on the size of the result.

Updated on: 2026-03-15T08:55:15+05:30

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements