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

3
  • 1
    Have a look at Integer.toString(...), Integer.parseInt(...), String.getBytes(...), and the String(byte[],...) methods and constructors. Commented Oct 29, 2014 at 1: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? Commented Oct 29, 2014 at 1:31
  • learn how to divide and multiply by 2... and learn how to read and write files byte by byte Commented Oct 29, 2014 at 1:53

2 Answers 2

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;
 }
}
Sign up to request clarification or add additional context in comments.

2 Comments

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.
right, didnt notice, just added some padding so it will always show 8 characters.
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);
    }
}

1 Comment

Only one debug run was required, I'm getting good at this :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.