Current Location: Home> Latest Articles> How to Use the bindec Function to Convert Binary Data Stored as a String in a Database to Decimal Numbers?

How to Use the bindec Function to Convert Binary Data Stored as a String in a Database to Decimal Numbers?

M66 2025-06-23

In practical applications, if you're reading data from a database, you can use PDO or mysqli to query, and then process it with bindec():

<?php  
// Connect to the database (using PDO as an example)  
$dsn = "mysql:host=m66.net;dbname=testdb;charset=utf8mb4";  
$username = "dbuser";  
$password = "dbpass";  
<p>try {<br>
$pdo = new PDO($dsn, $username, $password);</p>
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {  
    $binaryString = $row['binary_data'];  
    $decimalNumber = bindec($binaryString);  
    echo "Binary: $binaryString converted to Decimal: $decimalNumber\n";  
}  

} catch (PDOException $e) {
echo "Database connection failed: " . $e->getMessage();
}
?>

In the code above, it is assumed that the your_table table's field binary_data stores binary strings. We use bindec() to convert them into decimal numbers for further processing.

Summary

  • The bindec() function only accepts binary data in string format.

  • If reading binary strings from the database, ensure the field type is a character type (e.g., VARCHAR).

  • After conversion, bindec() returns a decimal integer, making it convenient for calculations or display.

With this approach, you can easily convert binary data stored as a string into decimal numbers, which is useful for processing and utilizing within your program.