如何将字节数组转换为Base64字符串?
时间: 2024-06-10 08:04:05 浏览: 11
可以使用Java中的Base64类来将字节数组转换为Base64字符串。下面是一个示例代码:
```java
import java.util.Base64;
public class Main {
public static void main(String[] args) {
// 示例字节数组
byte[] byteArray = {1, 2, 3, 4, 5};
// 使用Base64编码字节数组
String base64String = Base64.getEncoder().encodeToString(byteArray);
System.out.println("Base64字符串: " + base64String);
}
}
```
输出:
```
Base64字符串: AQIDBAU=
```
相关问题
将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类型来表示八位无符号整数数组。