user3002538
user3002538

Reputation: 15

How to Convert 8 bit to 16 bit?

I am trying to convert a string to 1 and 0 equivalent to the ASCII value of each character of String, its a kind of encoding. My code is giving me 8 bit results and I need 16 bit results for every character e.g. if my input string is 1A, then i am getting 0011000101000001 but desired output is 00000000001100010000000001000001. I want to have 8 extra zeros to make it 16 bit code. I am not suppose to use any third party method. Please give your suggestion on how to make it 16 bit. Also share your views on whether it is possible to decode the 16 bit back to 1A

  try(FileReader f=new FileReader(myFile)) 
    {

      int i;
      while((i=f.read())!=-1)
      {
      char c = (char)i;
      String s = Character.toString(c);

      byte[] bytes= s.getBytes();
      StringBuilder binary = new StringBuilder();

      for (byte b : bytes)
      {
         int val = b;
         for (int k = 0; k < 8; k++)
         {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
         }
      }
      System.out.print(binary);
  }
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Upvotes: 0

Views: 2672

Answers (2)

Marko Topolnik
Marko Topolnik

Reputation: 200168

You seem to want the character encoded in UTF-16 instead of the (probable) default of UTF-8. So, just change this line

byte[] bytes= s.getBytes();

to

byte[] bytes= s.getBytes("UTF-16BE");

Upvotes: 2

hasan
hasan

Reputation: 24185

for (byte b : bytes)
{
    int val = b;
    for (int k = 0; k < 8; k++) binary.append(0);
    for (int k = 0; k < 8; k++)
    {
        binary.append((val & 128) == 0 ? 0 : 1);
        val <<= 1;
    }
}

Upvotes: 0

Related Questions