Advertisement
stephanheijl

Binary String to ASCII example

Apr 28th, 2013
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.33 KB | None | 0 0
  1. /** Binary String to ASCII characters conversion
  2.     This is an untested example and may or may not work as advertised
  3.     @author: Stephan Heijl
  4. */
  5.  
  6. public static String bin2text ( String binary ) {
  7.     int pieceNo = (int)(binary.length/8) // Number of pieces
  8.    
  9.     // We'll use StringBuilder as we'll be doing a lot of concatenations
  10.     StringBuilder text = new StringBuilder();
  11.    
  12.     for( int p = 0; p < pieceNo ; p++ ) {
  13.         String piece = "";
  14.         try {
  15.             piece = binary.substring( p*8, (p+1)*8 ); // This should be an 8 character long piece of the binary string
  16.         } catch( java.lang.StringIndexOutOfBoundsException e ) {
  17.             // If this is reached the binary string is not a multiple of eight, so we compensate by padding the number with 0's.
  18.             piece = binary.substring( p*8 )        
  19.             // This might need some work
  20.             while ( piece.length < 8 ) {
  21.                 piece = "0" + piece
  22.             }
  23.         }
  24.        
  25.         // The following two steps could be done in a single line, but I will leave this for clarity
  26.        
  27.         // First convert the binary string to an int
  28.         int binValue = Integer.parseInt(piece, 2);
  29.         // now convert that to a char
  30.         char binCharacter = (char)binValue;
  31.        
  32.         // And append this to the whole string.
  33.         text.append( String.valueOf( binCharacter ) );
  34.     }
  35.    
  36.     // Convert the StringBuilder instance into a String to write to a file
  37.     return text.toString();
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement