简体   繁体   中英

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 eg 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();
}

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");
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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM