将 base64 字符串转换为 php 中的 integer/float/char 数组

string base64 to integer/float/char array in php

我想将 base64 字符串转换为其他类型,即整数、浮点数和字符数组。

在 Java 中,我可以使用 ByteBuffer 对象,因此使用 stream.getInt()stream.getLong()stream.getChar()stream.getFloat(),等等

但是如何在 PHP 中执行此操作?

编辑:我试过 base64-decode PHP 函数,但是这个函数解码字符串,我想解码数字。

编辑2:

在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());
        }
    }
}

显示105795

但是在php:

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

显示 0,因为 base64_decode('AAGdQw==') 不可打印。

按原样解码内容并通过type casting or some varialbe handling function such as settype()将结果转换为任何类型。

如果编码后的文件很大,担心占用内存,可以使用stream filters (relevant answer).

你必须使用 unpack 将解码后的字符串转换为字节数组,然后你可以从中重建整数:

<?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)

浮点数可以用 pack 函数重新组装,它从字节数组创建一个变量。

但请注意,您必须非常注意数据类型和底层硬件;特别是处理器的字节序(字节顺序)和处理器的字长(32 位 int 不同于 64 位 int)——因此,如果可能的话,你应该使用基于文本的协议,比如 JSON——你可以也是 base64 编码。