3

I want to read text from file which is "Hello" and then I want to convert this text to corresponding Binary form like:

01001000 01100101 01101100 01101100 01101111

Now, I after binary conversion, I want to again convert the same

01001000 01100101 01101100 01101100 01101111

to Hello and write it to file

And How can the same be done for multiple words like "Hello World my name is XYZ"

How can I possibly do that? Please help

Pavitra Kansara
  • 819
  • 8
  • 14
  • 1
    Have a look at Integer.toString(...), Integer.parseInt(...), String.getBytes(...), and the String(byte[],...) methods and constructors. – President James K. Polk Oct 29 '14 at 01:29
  • @GregS `BitSet` could also be deployed on the result of String.getBytes, if direct programmatic bit access is required. There must be some use case for that class? – Maarten Bodewes Oct 29 '14 at 01:31
  • learn how to divide and multiply by 2... and learn how to read and write files byte by byte – CharlieS Oct 29 '14 at 01:53

2 Answers2

4

I didnt go into detail on how to read/write files, since you can look that up. However, to achieve what you want:

  • you will need a method to convert a word to binary
  • then you will need another method to convert from binary to words

below is the code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class HelloWorld{

 public static void main(String []args) throws FileNotFoundException {
   File file = new File("input.txt");
   Scanner sc = new Scanner(file);
   String word=sc.nextLine();
   String receivedBinary=stringToBinary(word);
   System.out.println();
   String receivedWord=BinaryToString(receivedBinary);
 }
 public static String stringToBinary(String text)
 {
     String bString="";
     String temp="";
     for(int i=0;i<text.length();i++)
     {
         temp=Integer.toBinaryString(text.charAt(i));
         for(int j=temp.length();j<8;j++)
         {
             temp="0"+temp;
         }
         bString+=temp+" ";
     }

     System.out.println(bString);
     return bString;
 }
 public static String BinaryToString(String binaryCode)
 {
     String[] code = binaryCode.split(" ");
     String word="";
     for(int i=0;i<code.length;i++)
     {
         word+= (char)Integer.parseInt(code[i],2);
     }
     System.out.println(word);
     return word;
 }
}
luisluix
  • 547
  • 5
  • 17
  • It's a bit of a shame that `Integer.toBinaryString` doesn't always print all bits of a byte, maybe you should subroutine that. `word+= (char)Integer.parseInt(code[i],2);` doesn't feel correct. – Maarten Bodewes Oct 29 '14 at 02:08
  • right, didnt notice, just added some padding so it will always show 8 characters. – luisluix Oct 29 '14 at 02:33
0

OK, because I like puzzling and because the Java language could have more support for this kind of low level array operations. I've coined the term bitgets to indicate the character representation of a 0 and 1, and a method toBitgets to print all 8 bits of a byte.

This class also uses some regex fu to make sure that the parsed string has the exact representation that was requested of it: 8 bitgets followed by a space or the end of the input.

import static java.nio.charset.StandardCharsets.US_ASCII;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class S2B2S {

    public S2B2S() {

    }

    public void toBitgets(StringBuilder sb, byte b) {
        for (int i = 0; i < Byte.SIZE; i++) {
            sb.append('0' + ((b >> (Byte.SIZE - i - 1))) & 1);
        }
    }

    public String encode(String s) {
        byte[] sdata = s.getBytes(US_ASCII);
        StringBuilder sb = new StringBuilder(sdata.length * (Byte.SIZE + 1));
        for (int i = 0; i < sdata.length; i++) {
            if (i != 0) {
                sb.append(' ');
            }
            byte b = sdata[i];
            toBitgets(sb, b);
        }
        return sb.toString();
    }

    public String decode(String bs) {
        byte[] sdata = new byte[(bs.length() + 1) / (Byte.SIZE + 1)];
        Pattern bytegets = Pattern.compile("([01]{8})(?: |$)");
        Matcher bytegetsFinder = bytegets.matcher(bs);
        int offset = 0, i = 0;
        while (bytegetsFinder.find()) {
            if (bytegetsFinder.start() != offset) {
                throw new IllegalArgumentException();
            }
            sdata[i++] = (byte) Integer.parseInt(bytegetsFinder.group(1), 2);

            offset = bytegetsFinder.end();
        }
        if (offset != bs.length()) {
            throw new IllegalArgumentException();
        }
        return new String(sdata, US_ASCII);
    }

    public static void main(String[] args) {
        String hello = "Hello";
        S2B2S s2b2s = new S2B2S();
        String encoded = s2b2s.encode(hello);
        System.out.println(encoded);
        String decoded = s2b2s.decode(encoded);
        System.out.println(decoded);
    }
}
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263