5

I was thinking to use this:

<?php
$string1 = 'V2h5IEkgY2FuJ3QgZG8gdGhpcyEhISEh';
echo base64_decode($string1);
?>

The output for this example should always be 18 characters! But sometimes this output is less than 18.

24 (base64 characters) multiplied by 6 (bits per base64 character) equals to 144 (bits) divided by 8 (bits per ASCII character) equals to 18 ASCII characters.

The problem is that the output is displayed in plain text; and some characters don't even have a "text representation" and that data will be lost. The next test will show that there are 41 different ASCII characters with no visible output.

<?php
for ($i = 0; $i <= 255; $i++) {
    $string2 = chr($i);
    echo $i . " = " . $string2 . "<br>";
}
?>

My plan was to decode the base64 string and from the output in ASCII reconvert it to hexadecimal. Now that is not possible because of those 41 characters.

I also tried base_convert but there is no base64 support for it.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
cronos
  • 536
  • 2
  • 8
  • 20
  • 4
    `bin2hex()` is a built-in function you might be interested in. – mario Jun 06 '16 at 00:59
  • 3
    Possible duplicate of [Convert base64'd SHA1 hashes to Hex hashes](http://stackoverflow.com/questions/2914504/convert-base64d-sha1-hashes-to-hex-hashes) – zanderwar Jun 06 '16 at 01:01
  • 2
    See http://stackoverflow.com/questions/2914504/convert-base64d-sha1-hashes-to-hex-hashes – zanderwar Jun 06 '16 at 01:01

3 Answers3

8

You can do this with bin2hex():

Returns an ASCII string containing the hexadecimal representation of str. The conversion is done byte-wise with the high-nibble first.

php > $string1 = 'V2h5IEkgY2FuJ3QgZG8gdGhpcyEhISEh';
php > echo base64_decode($string1);
Why I can't do this!!!!!
php > echo bin2hex(base64_decode($string1));
57687920492063616e277420646f20746869732121212121
php >
Will
  • 24,082
  • 14
  • 97
  • 108
2
<?php
$string1 = 'V2h5IEkgY2FuJ3QgZG8gdGhpcyEhISEh';
$binary = base64_decode($string1);
$hex = bin2hex($binary);
echo $hex;
?>
cronos
  • 536
  • 2
  • 8
  • 20
1

A simple one line solution is:

<?=bin2hex(base64_decode($string1));?>
Omair Munir
  • 135
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 27 '21 at 10:43