Pryach
Pryach

Reputation: 417

PHP Binary to Hex with leading zeros

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.

Upvotes: 3

Views: 14726

Answers (3)

netgenius.co.uk
netgenius.co.uk

Reputation: 169

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

Upvotes: 13

hek2mgl
hek2mgl

Reputation: 158010

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

Upvotes: 7

Jon
Jon

Reputation: 437386

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.

Upvotes: 1

Related Questions