PHP Binary to Hex with leading zeros

12,338

Solution 1

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?

  1. It finds out how many leading zeroes your binary string has with strspn.
  2. It translates this to the number of leading zeroes you need on the hex representation. Whole groups of 4 leading zero bits need to be translated to one zero hex digit; any leftover zero bits are already encoded in the first nonzero hex digit of the output, so we use floor to cast them out.
  3. It prepends that many zeroes to the result using 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.

Solution 2

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));

Solution 3

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);
Share:
12,338
Pryach
Author by

Pryach

Updated on June 04, 2022

Comments

  • Pryach
    Pryach almost 2 years

    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.