Skip to content

Instantly share code, notes, and snippets.

@JarvisCraft
Last active July 14, 2019 16:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JarvisCraft/0b28c9027483c06a9bc57c37c1b6b780 to your computer and use it in GitHub Desktop.
Save JarvisCraft/0b28c9027483c06a9bc57c37c1b6b780 to your computer and use it in GitHub Desktop.
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
Copy link

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