I converted byte array bytes to String. But when calculating the bytes in the string, I am not getting correct answer. The size of bytes is 125, but I'm getting 129.
The code is given below:
String s2= null;
try {
System.out.println(bytes.length); //This gives 125 as answer
s2 = new String(bytes,"UTF-8");
System.out.println(s2.getBytes("UTF-8").length); //But this gives 129 instead of 125
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
What is wrong with above code?
EDIT: Based on the answers given below, bytes is encoded in the wrong format. If initialization of bytes done as shown below, then how to convert bytes to string without
losing(or gaining) any extra data?
byte[] bytes=new byte[125];
for (int i = 0; i < 125; i++) {
bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
}
Update: If I remove the shift operation in above code it is giving correct output. What is the problem with shifting?
bytes. Can you give us the original byte array?byte[] bytes = new byte[125];1.7.0_45-b18