cronos cronos - 1 year ago 243
PHP Question

how to convert from base64 to hexadecimal in php?

I was thinking to use this:

$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 ASCCI character with no visible output.

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.

Answer Source

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));
php >
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download