2

I have an issue while encoding and decoding string. If i encode string a to b then b to c means it works fine. If I convert finalstring means I got some extra characters. Please view my output for your clarifications am getting extra character at the end in output.

Here is my code.

public class DoubleByteReverse {

   public static void main(String args[]) {



      try{                    
             String a = new String("基本形");

             System.out.println("a value "+a);

             String b=new String(a.getBytes("Cp939"), "Cp500");

             System.out.println("b value "+b);

             String c=new String(b.getBytes("Cp500"), "Cp939");

             System.out.println("c value "+c);

             String g = new String("ã1áÃã°");

             String x = "0x0E";
            byte[] bytes = hexStringToByteArray(x);
            String st = new String(bytes,"Cp500");
            //System.out.println(st);

             String y = "0x0F";
            byte[] bytes1 = hexStringToByteArray(y);
            String en = new String(bytes1,"Cp500");
            //System.out.println(en);


             String finalstring =new String(st+g+en);

             System.out.println("whole string "+finalstring);

             String output=new String(finalstring.getBytes("Cp500"),"Cp939");

             System.out.println("output  "+output);

              }
             catch (UnsupportedEncodingException e){}
      }


   public static byte[] hexStringToByteArray(String hex) {
       int l = hex.length();
       byte[] data = new byte[l/2];
       for (int i = 0; i < l; i += 2) {
           data[i/2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4)
                                + Character.digit(hex.charAt(i+1), 16));
       }
       return data;
   }


}

Output:

a value 基本形 
b value ã1áÃã° 
c value 基本形 
whole string ã1áÃã° 
output  基本形�
3
  • Change encoding to UTF-8. Commented Apr 7, 2016 at 13:29
  • @piyush121 I saved using UTF-8 only Commented Apr 7, 2016 at 13:31
  • I think the 0x prefix on your strings x and y shouldn't be there - the hexStringToByteArray is trying to convert the prefix into a byte as well. Just use 0E and 0F Commented Apr 7, 2016 at 13:57

2 Answers 2

1

It seems that what you do in hexStringToByteArray is not working properly but if you change the value of finalstring for this value new String("\u000E" + g + "\u000F") it works as expected.

Sign up to request clarification or add additional context in comments.

Comments

0

Try using :

Import this > import javax.xml.bind.DatatypeConverter; DatatypeConverter.printHexBinary(bytes)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.