Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /** 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 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
- }
- }
- // The following two steps could be done in a single line, but I will leave this for clarity
- // 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 text.toString();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement