Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Base2 encoder 4j
class Base2Encoder {
public static final int CHAR_SIZE = 16;
public static final char POSITIVE_SYMBOL = ')';
public static void main(String[] args) {
final String encoded = toBase2("Hello world!");
System.out.printf("Encoded: %s%n", encoded);
System.out.printf("Decoded: %s%n", fromBase2(encoded));
}
public static String toBase2(final String decoded) {
final StringBuilder encoded = new StringBuilder(decoded.length() * CHAR_SIZE);
{
String tmpString;
int tmpDif;
for (final char character : decoded.toCharArray()) {
tmpString = Integer.toBinaryString(character).replace('1', POSITIVE_SYMBOL);
tmpDif = CHAR_SIZE - tmpString.length();
for (int i = 0; i < tmpDif; i++) encoded.append('0');
encoded.append(tmpString);
}
}
return encoded.toString();
}
public static String fromBase2(final String encoded) {
final int length = encoded.length();
final StringBuilder decoded = new StringBuilder(length / CHAR_SIZE);
{
for (int i = 0; i < length; i += 16) decoded
.append((char) Integer.parseInt(encoded.substring(i, i + 16).replace(POSITIVE_SYMBOL, '1'), 2));
}
return decoded.toString();
}
}
@xtrafrancyz

This comment has been minimized.

Copy link

@xtrafrancyz xtrafrancyz commented Jul 4, 2019

It's a very useful encoding algorithm. Thanks for the sharing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment