Base 64 解码为 String 不符合预期

Base 64 decode to String not as expected

我有一个字符串,我想将其解码为二进制对象(BigInteger 或其字符串) 比如说我得到了 String

String str = "LTEwMTAwMTEwMTExMA==";

现在我想使用Base64.getDecoder()方法对其进行解码,例如:

String result = new BigInteger(Base64.getDecoder().decode(str.getBytes("UTF-8"))).toString(2);

据此,result的值为

101101001100010011000000110001001100000011000000110001001100010011000000110001001100010011000100110000

这与我使用任何在线解码器获得的结果不匹配:

-101001101110

你能帮帮我吗?我究竟做错了什么? 非常感谢!

Base64.Decoder.decode() 生成的是字节数组,不是字符串,所以需要进行转换。然后你可以使用接受基数的 BigInteger 构造函数来指定基数 2:

import java.io.IOException;
import java.math.BigInteger;
import java.util.Base64;

public class Test
{
    public static void main(String args[]) throws IOException
    {
        String str = "LTEwMTAwMTEwMTExMA==";
        String str2 = new String(Base64.getDecoder().decode(str), "UTF-8");
        BigInteger big = new BigInteger(str2, 2);
        System.out.println(big.toString(2));
    }
}

输出:

-101001101110

您的字符串转换有问题 - 试试这个:

String result = new BigInteger(new String(Base64.getDecoder().decode(encoded.getBytes("UTF-8")))).toString();

通过使用新的 String 构造函数将字节数组转换为 String,您将获得 BigInteger 构造函数知道如何解析的简单 String 表示形式。结果将是预期的 -101001101110