[英]String with binary numbers to String Base64 - JAVA
I'm trying to convert an string with characters to another string in base64. 我正在尝试将带有字符的字符串转换为base64中的另一个字符串。 But, unfortunately i have not done it yet.
但是,遗憾的是我还没有完成它。
SO got this String: 11000110 01111111 10011100 10010111 00111101 11001011 01101011 11000110 01010110 10101001 11101010 01111010 10011110 00100001 得到这个字符串:11000110 01111111 10011100 10010111 00111101 11001011 01101011 11000110 01010110 10101001 11101010 01111010 10011110 00100001
And it should become: xn+clz3La8ZWqep6niE= 它应该成为:xn + clz3La8ZWqep6niE =
To transform from String Base64 to an string with binary I got it using this code: 要从String Base64转换为带二进制的字符串,我使用以下代码获取它:
public static void main(String[] args)
{
String s = new String("xlactz3Ja8Z/qep6niE=");
System.out.println("String: " + s);
byte[] b = Base64.getDecoder().decode(s);
String res = "";
String aux = new String();
for(byte a : b)
{
aux = Integer.toBinaryString(255 & a);
// If length is less than 8, than add "0"
if (aux.length() != 8) {
aux = padronize (aux);
}
res = res + aux + " ";
}
// Padronize all Substrings to have length 8
private static String padronize (String str) {
String aux = "";
// Create a auxiliar string to padronize
for (int i = 0; i < 8 - str.length(); i++) {
aux += "0";
}
return aux + str;
}
To convert from base64 string to the binary string your code is right, I wrote it in this way: 要从base64字符串转换为二进制字符串,您的代码是正确的,我用这种方式编写它:
public static String fromBase64ToBinaryString(String base64String){
byte[] b = Base64.getDecoder().decode(base64String);
String []result = new String[b.length];
for (int i=0;i<b.length;i++){
result[i] = String.format("%8s", Integer.toBinaryString(b[i] & 0xFF)).replace(' ', '0');
}
return String.join(" ", result);
}
To convert from binary String to the base64 string you can use this code: 要从二进制String转换为base64字符串,您可以使用以下代码:
public static String fromBinaryStringToBase64(String binary) {
String[] split = binary.split(" ");
byte[] arrayBinary = new byte[split.length];
for(int i=0;i<split.length;i++){
arrayBinary[i] = (byte)Integer.parseInt(split[i],2);
}
return Base64.getEncoder().encodeToString(arrayBinary);
}
here the sample code in order to call the two methods: 这里是示例代码,以便调用这两个方法:
String s = "xn+clz3La8ZWqep6niE=";
String fromBase64ToBinaryString = fromBase64ToBinaryString( s);
System.out.println(fromBase64ToBinaryString);
String binary = "11000110 01111111 10011100 10010111 00111101 11001011 01101011 11000110 01010110 10101001 11101010 01111010 10011110 00100001";
String fromBinaryStringToBase64 = fromBinaryStringToBase64(binary);
System.out.println(fromBinaryStringToBase64);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.