Open In App

How to Convert Binary to Hexadecimal in PHP?

Last Updated : 30 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Number, the task is to convert Binary number to Hexadecimal Number in PHP. There are different approaches to convert a binary number to its hexadecimal representation using PHP. Hexadecimal (base-16) is commonly used in computing because it’s more compact than binary and easier to read than binary or decimal.

Approach 1: Using bindec() and dechex() Functions

First, we take a Binary input and then use bindec() function to convert Binary to Decimal equivalent, and then use dechex() function to convert decimal number to its Hexadecimal equivalent.

PHP
<?php

// Bunary Number
$bin = '110110101011';

// Convert Binary to Decimal 
// and then Decimal to Hex
$hex = dechex(bindec($bin));

echo $hex;

?>

Output
dab

Approach 2: Using base_convert() Function

This code snippet converts a binary number to its hexadecimal equivalent using PHP’s base_convert() function. The base_convert() function in PHP is used to convert a number given in an arbitrary base to a desired base.

PHP
<?php

// Bunary Number
$bin = '110110101011';

// Convert Binary to Hex
$hex = base_convert($bin, 2, 16);

echo $hex;

?>

Output
dab

Approach 3: Using Custom Conversion Logic

We can convert binary to hexadecimal manually by iterating over each nibble (4 bits) of the binary number and converting it to its hexadecimal equivalent.

PHP
<?php

function binToHex($bin) {
    $hex = '';
    $len = strlen($bin);
    for ($i = $len - 1; $i >= 0; $i -= 4) {
        $nibble = substr($bin, max(0, $i - 3), min(4, $i + 1));
        $hex = dechex(bindec($nibble)) . $hex;
    }
    return $hex;
}

// Driver Code
// Bunary Number
$bin = '110110101011';

// Convert Binary to Hex
$hex = binToHex($bin);

echo $hex;

?>

Output
dab

Explanation:

  • We iterate over the binary number in groups of 4 bits (nibbles).
  • For each nibble, we convert it to decimal using bindec() and then to hexadecimal using dechex().
  • We concatenate the hexadecimal representation of each nibble to get the final hexadecimal number.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads