Reputation: 89
I need to convert a binary String ("110100", 52 in decimal) to its corresponding Base64 character, that I know is "0". Is any way in Java to do that? I was reading multiple base 64 guides but I cant reach the answer.
For clarification, the conversion table is here: https://www.lifewire.com/base64-encoding-overview-1166412 (Base64 Encoding Table section) I want having the 52, convert it to "0" char.
Thanks a lot.
Upvotes: 0
Views: 685
Reputation: 439
Since a byte is 8 bits long and Base64 makes up its values by grabbing only 6 bits the simplest way I can think of is appending two characters at the beginning of your desired character and taking only the last character of the result:
String encode = String.format("00%s", (char) Integer.parseInt("110100", 2));
String encoded = new String(Base64.getEncoder().encode(encode.getBytes()));
System.out.println(encoded.charAt(encoded.length() - 1));
// Prints: 0
Upvotes: 1
Reputation: 5289
You first need to convert your binary string into a byte array. There are a number of posts on how to accomplish this but in pseudo code it would look like the following.
Read up to 4 characters;
Byte.parseByte(chars, 2);
Append to byte array;
Then you can use Base64.Encoder to encode the bytes.
Upvotes: 0