Last active
July 14, 2019 16:45
-
-
Save JarvisCraft/0b28c9027483c06a9bc57c37c1b6b780 to your computer and use it in GitHub Desktop.
Base2 encoder 4j
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's a very useful encoding algorithm. Thanks for the sharing.