Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert from base64 to hexadecimal in php?

Tags:

php

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.

like image 739
cronos Avatar asked Mar 13 '23 02:03

cronos


1 Answers

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 >
like image 183
Will Avatar answered Mar 15 '23 04:03

Will