Convert a bit to Base64 character

Tags: ,



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.

Answer

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


Source: stackoverflow