Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stackoverflowtests;
- /**
- *
- * @author Stephan
- */
- public class StackOverflowTests {
- public static void main(String[] args) {
- // This Binary string is bin for 128256128256
- String bin1 = "00111111100011010011111110001101001111111000110100111111100011010011111110001101";
- String text = bin2text(bin1);
- System.out.println(text);
- String bin2 = text2bin(text);
- System.out.println(bin1);
- System.out.println(bin2);
- System.out.println(bin1.equals( bin2 ));
- }
- /**
- * Binary String to ASCII characters conversion This is an untested example
- * and may or may not work as advertised
- *
- * @author: Stephan Heijl
- */
- public static String bin2text(String binary) {
- int mod = 0; // Indicates the extra padding on the last character
- int pieceNo = (int) (binary.length() / 8); // Number of pieces
- // We'll use StringBuilder as we'll be doing a lot of concatenations
- StringBuilder text = new StringBuilder();
- for (int p = 0; p <= pieceNo; p++) {
- String piece = "";
- try {
- piece = binary.substring(p * 8, (p + 1) * 8); // This should be an 8 character long piece of the binary string
- } catch (java.lang.StringIndexOutOfBoundsException e) {
- // If this is reached the binary string is not a multiple of eight, so we compensate by padding the number with 0's.
- piece = binary.substring(p * 8); // This might need some work
- while (piece.length() < 8) {
- piece = "0" + piece;
- mod++;
- }
- }
- // First convert the binary string to an int
- int binValue = Integer.parseInt(piece, 2);
- // now convert that to a char
- char binCharacter = (char) binValue;
- // And append this to the whole string.
- text.append(String.valueOf(binCharacter));
- }
- // Convert the StringBuilder instance into a String to write to a file
- return String.valueOf(mod) + text.toString();
- }
- /**
- * Reverse text => Binary String method Also untested, binary to string at:
- * http://pastebin.com/KEYV8jgx
- */
- public static String text2bin(String text) {
- StringBuilder binary = new StringBuilder();
- int mod = Integer.parseInt(text.substring(0,1));
- text = text.substring(1);
- for (int c = 0; c < text.length(); c++) {
- // Get the char at each position in the text, cast it to an int
- int n = (int) text.charAt(c);
- // Turn the integer into a binary String (01010101)
- String binString = Integer.toBinaryString(n);
- // Add it to the StringBuilder
- while (binString.length() < 8) {
- binString = "0" + binString;
- }
- if ( c == text.length()-1 ) {
- binString = binString.substring(mod);
- }
- binary.append(binString);
- }
- // Convert the StringBuilder instance into a String to decode
- return binary.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement