Reputation: 5946
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.
Upvotes: 0
Views: 2227
Reputation: 3568
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.
Upvotes: 4
Reputation: 2743
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).
Upvotes: 0