java将base64编码字符串还原为字节数组
时间: 2023-12-22 22:06:34 浏览: 28
在Java中,可以使用java.util.Base64类来将Base64编码的字符串还原为字节数组。具体实现可以参考以下代码:
```java
import java.util.Base64;
public class Base64Test {
public static void main(String[] args) {
String encoded = "SGVsbG8sIFdvcmxkIQ==";
// 解码
byte[] decoded = Base64.getDecoder().decode(encoded);
System.out.println("Base64解码后字节数组:" + new String(decoded));
}
}
```
在上面的代码中,我们首先定义了一个Base64编码后的字符串,然后使用Base64解码器对其进行解码,得到字节数组。最后,我们将字节数组转换为字符串并输出。可以看到,经过解码后得到的字节数组与我们最初编码时使用的字节数组是一致的。
相关问题
将Base64字符串解码为八位字节数组
好的,可以使用Java中的Base64类中的decode方法将Base64字符串解码为字节数组,然后再转换为八位字节数组。以下是一个示例代码:
```java
import java.util.Base64;
public class Main {
public static void main(String[] args) {
String base64String = "SGVsbG8gV29ybGQh";
byte[] decodedBytes = Base64.getDecoder().decode(base64String);
byte[] eightBitBytes = new byte[decodedBytes.length];
for (int i = 0; i < decodedBytes.length; i++) {
eightBitBytes[i] = (byte) (decodedBytes[i] & 0xFF);
}
System.out.println("Decoded bytes: " + Arrays.toString(eightBitBytes));
}
}
```
输出结果为:
```
Decoded bytes: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
```
其中,Base64字符串 "SGVsbG8gV29ybGQh" 解码后为字节数组 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33],再转换为八位字节数组即为输出结果。
js将Base64字符串解码为八位字节数组
可以使用JavaScript中的atob()方法将Base64字符串解码为字节数组,然后再转换为八位字节数组。以下是一个示例代码:
```javascript
const base64String = "SGVsbG8gV29ybGQh";
const decodedBytes = atob(base64String).split("").map(function(c) {
return c.charCodeAt(0);
});
const eightBitBytes = new Uint8Array(decodedBytes);
console.log("Decoded bytes: " + eightBitBytes);
```
输出结果为:
```
Decoded bytes: Uint8Array(12) [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
```
其中,Base64字符串 "SGVsbG8gV29ybGQh" 解码后为字节数组 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33],再转换为八位字节数组即为输出结果。注意,在JavaScript中,需要使用Uint8Array类型来表示八位无符号整数数组。