I have the follow code:
$binary = \"110000000000\";
$hex = dechex(bindec($binary));
echo $hex;
?>
Which works fine, and I get a valu
You can do it very easily with sprintf:
// Get $hex as 3 hex digits with leading zeros if required.
$hex = sprintf('%03x', bindec($binary));
// Get $hex as 4 hex digits with leading zeros if required.
$hex = sprintf('%04x', bindec($binary));
To handle a variable number of bits in $binary:
$fmt = '%0' . ((strlen($binary) + 3) >> 2) . 'x';
$hex = sprintf($fmt, bindec($binary));
Use str_pad() for that:
// maximum number of chars is maximum number of words
// an integer consumes on your system
$maxchars = PHP_INT_SIZE * 2;
$hex = str_pad($hex, $maxchars, "0", STR_PAD_LEFT);
You can prepend the requisite number of leading zeroes with something such as:
$hex = str_repeat("0", floor(strspn($binary, "0") / 4)).$hex;
What does this do?
strspn
.floor
to cast them out.str_repeat
.Note that if the number of input bits is not a multiple of 4 this might result in one less zero hex digit than expected. If that is a possibility you will need to adjust accordingly.