I have the follow code:
<?
$binary = "110000000000";
$hex = dechex(bindec($binary));
echo $hex;
?>
Which works fine, and I get a value of c00.
However, when I try to convert 000000010000 I get the value "10". What I actually want are all the leading zeros, so I can get "010" as the final result.
How do I do this?
EDIT: I should point out, the length of the binary number can vary. So $binary might be 00001000 which would result it 08.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With