Search code examples
phptype-conversionhexbin

How to properly convert HEX to BIN in PHP7?


I am trying to convert HEX value "0000" into BIN value. In math: (0000)16 = (0000 0000 0000 0000)2

but when I am trying to use

$hex = '0000';
echo base_convert ($hex, 16, 2);

I am getting 0 insted of 0000 0000 0000 0000.

It looks the same but is not. In my scenario, the 16 bits represent the status of digital outputs saved as HEX value.

What do I need to change, to make it work as expected?


Solution

  • You are getting 0 because base_convert will not output any more digits into the result string than are necessary to represent the number. Instead, use hexdec to convert the string to a decimal number and then use sprintf to get the output as 16 binary digits using the %b conversion specification:

    $hex = '0000';
    $bin = sprintf("%016b", hexdec($hex));
    echo $bin;
    

    Output:

    0000000000000000
    

    If you really want spaces between each block of 4 bits, you can use str_split and implode e.g.

    echo implode(' ', str_split($bin, 4)) . "\n";
    

    Output:

    0000 0000 0000 0000
    

    Demo on 3v4l.org