0

I would like to convert a base64 string to other types, ie integer, float, and char array.

In Java I can use a ByteBuffer object, so it's easy to get values with methods like stream.getInt(), stream.getLong(), stream.getChar(), stream.getFloat(), etc.

But how to do this in PHP?

Edit: I tried the base64-decode PHP function, but this one decode a string, I want to decode numbers.

Edit2:

In Java:

import java.nio.ByteBuffer;
import javax.xml.bind.DatatypeConverter;

public class Main {

    public static void main(String[] args) {
        ByteBuffer stream = ByteBuffer.wrap(DatatypeConverter.parseBase64Binary("AAGdQw=="));
        while (stream.hasRemaining()) {
            System.out.println(stream.getInt());
        }
    }
}

displays 105795

But in php:

$nb = base64_decode('AAGdQw=='); // the result is not a stringified number, neither printable
settype($nb, 'int');
echo $nb;

displays 0, because base64_decode('AAGdQw==') is not printable.

roipoussiere
  • 5,142
  • 3
  • 28
  • 37

2 Answers2

4

you have to use unpack to convert the decoded string into a byte array, from which you then can reconstruct the integer:

<?php
$s = 'AAGdQw==';
$dec = base64_decode($s);
$ar = unpack("C*", $dec);
$i= ($ar[1]<<24) + ($ar[2]<<16) + ($ar[3]<<8) + $ar[4];

var_dump($i);
//output int(105795)

floats could be re-assembled with the pack-function, which creates a variable from a byte array.

but be advised that you have to take a lot of care about both data types AND the underlying hardware; especially the endianness (byte order) of the processor and the word size of the processor (32bit int differs from 64bit int) - therefore, if possible, you should use a text-based protocol, like JSON - which you can base64-encode, too.

Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30
0

Decode a content as is and cast a result to any type through type casting or some varialbe handling function such as settype().

If encoded file is large and you worried about memory consumption, you can use stream filters (relevant answer).

Community
  • 1
  • 1
Timurib
  • 2,735
  • 16
  • 29
  • Thank you. I tried but I don't understand why `settype(base64_decode('AAGdQw=='), 'int')` returns `1`. – roipoussiere Nov 18 '16 at 10:42
  • `settype()` accepts argument by reference (see the manual), so you need to assign decoding result to a variable and apply `settype`. Also you can use [`intval()`](http://php.net/manual/en/function.intval.php). – Timurib Nov 18 '16 at 10:47
  • Works better. The fact is my base64 string do not contains a stringified integer, it contains the integer itself: ie `AAGdQw==` is supposed to be `105795`, but the decoded string is not printable, so I don't think I can use it with `intval()`. See my edit. – roipoussiere Nov 18 '16 at 11:14