📜  将 base64 解码为字符串 (1)

📅  最后修改于: 2023-12-03 15:25:13.128000             🧑  作者: Mango

将 base64 解码为字符串

在网络传输或存储数据时,常常需要将数据进行编码或解码。其中,Base64 是一种常见的编码方式,通常用于将二进制数据转换为文本数据。在某些场景下,我们需要将 Base64 编码的字符串解码为原始的二进制数据或字符串。本文介绍如何使用不同编程语言将 Base64 解码为字符串。

Python

在 Python 中,可以使用 base64 模块提供的 b64decode() 函数将 Base64 编码解码为原始数据。下面是示例代码:

import base64

base64_str = "dGhpcyBpcyBhIHJlYWwgb2YgdGVzdCByZXBvc2l0b3J5"
decoded_str = base64.b64decode(base64_str).decode("utf-8")

print(decoded_str)

输出的结果是:

this is a real of test report

首先,将需要解码的 Base64 字符串传递给 b64decode() 函数,该函数会返回一个二进制数据对象。然后,我们使用 decode() 方法将二进制数据对象解码为字符串对象。

Java

在 Java 中,可以使用 java.util.Base64 类提供的 getDecoder() 方法实现 Base64 解码。下面是示例代码:

import java.util.Base64;

String base64Str = "dGhpcyBpcyBhIHJlYWwgb2YgdGVzdCByZXBvc2l0b3J5";
byte[] decodedBytes = Base64.getDecoder().decode(base64Str);
String decodedStr = new String(decodedBytes, "utf-8");

System.out.println(decodedStr);

输出的结果同样是:

this is a real of test report

在 Java 中,我们将需要解码的 Base64 字符串传递给 getDecoder().decode() 方法,该方法将返回一个字节数组。然后,我们使用 String 类的构造函数将字节数组解码为字符串对象。

JavaScript

在 JavaScript 中,可以使用 atob() 函数将 Base64 字符串解码为原始数据(二进制数据),并使用 decodeURIComponent() 函数将二进制数据解码为字符串。下面是示例代码:

const base64Str = "dGhpcyBpcyBhIHJlYWwgb2YgdGVzdCByZXBvc2l0b3J5";
const decodedStr = decodeURIComponent(Array.prototype.map.call(atob(base64Str), (c) => {
    return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2);
}).join(""));

console.log(decodedStr);

同样地,输出结果为:

this is a real of test report

在 JavaScript 中,我们首先使用 atob() 函数将 Base64 编码解码为原始数据。然后,我们使用 map() 函数将原始数据转换为可解码的字符串格式,并使用 join() 函数将字符串拼接起来。最后,我们使用 decodeURIComponent() 函数将字符串解码为原始字符串。

总结

无论是 Python、Java 还是 JavaScript,我们都可以使用一些内置函数或类库将 Base64 编码解码为原始数据或字符串。在实际开发中,需要根据不同的场景选择适合的解码方式。