How to use hexdec() and decbin() Functions In PHP
This PHP code defines a function hexToBin() that converts a hexadecimal number to a binary number. It converts the hexadecimal number to a decimal number, then to a binary number, and add the binary padding representation with leading zeros to ensure each hexadecimal character corresponds to 4 bits. The function is demonstrated by converting the hexadecimal value “DA” to its padded binary equivalent, which is echoed as 00011010.
Example: This example shows the implementation of the above-mentioned approach.
<?php
function hexToBin($hex) {
$decimal = hexdec($hex);
$binary = decbin($decimal);
$paddedBinary = str_pad(
$binary,
strlen($hex) * 4,
'0',
STR_PAD_LEFT
);
return $paddedBinary;
}
// Driver Code
$hexVal = "DA";
$binVal = hexToBin($hexVal);
// Output: 00011010
echo $binVal;
?>
Output
11011010
Hexadecimal to Binary Converter in PHP
Hexadecimal and binary are two number systems commonly used in computing. Hexadecimal (base 16) is often used to represent binary values in a more human-readable format. Hexadecimal to Binary converter is a common task in programming, especially when dealing with low-level operations or data manipulation.
Examples:
Input: hexValue = "1A" Output: 00011010 Input: hexValue = "DA" Output: 11011010