如何在Java中将int数组转换为base64字符串?
问题描述:
如何转换此阵:如何在Java中将int数组转换为base64字符串?
int[] ints = { 233, 154, 24, 196, 40, 203, 56, 213, 242, 96, 133, 54, 120, 146, 46, 3 };
为了这个字符串?
String base64Encoded = "6ZoYxCjLONXyYIU2eJIuAw==";
用法:
String base64Encoded = ConvertToBase64(int[] ints);
(我问这个问题,因为byte
在Java中签名,但byte
在C#是无符号数)
答
的问题可以被打破分为2个简单步骤:1.将int数组转换为一个字节数组。 2.将字节数组编码为base4。
这里有一个办法做到这一点:
public static String convertToBase64(int[] ints) {
ByteBuffer buf = ByteBuffer.allocate(ints.length);
IntStream.of(ints).forEach(i -> buf.put((byte)i));
return Base64.getEncoder().encodeToString(buf.array());
}
一个更老派的做法:
public static String convertToBase64(int[] ints) {
byte[] bytes = new byte[ints.length];
for (int i = 0; i < ints.length; i++) {
bytes[i] = (byte)ints[i];
}
return Base64.getEncoder().encodeToString(bytes);
}
请提供解释到答案! – Yahya
@shmosel:在你的例子中'int'不会被转换为一个签名的'byte'吗?这会产生一个不同的字符串。请看我的要求。 – JohnB
@JohnB您还没有发布任何要求,只是我的解决方案实现的示例输入和输出。 – shmosel