Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Binary to Hex with leading zeros

Tags:

php

hex

binary

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.

like image 537
Pryach Avatar asked Nov 24 '25 06:11

Pryach


2 Answers

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));
like image 183
netgenius.co.uk Avatar answered Nov 25 '25 20:11

netgenius.co.uk


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);
like image 30
hek2mgl Avatar answered Nov 25 '25 18:11

hek2mgl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!