Your ASCII contain some non printable character thats why its causing the problem.If you look into hex value of your string "adsfads" is equal to 61647366616473,While you have taken "61647366616473000000",here last "000000" non printable character.if you will remove those zero from your String then you will get the desired result by your code.or you can also replace the nonprintable character from your string to get the appropriate result.or you can write the code to check if the ascii char is not printable then assign some value to it as,
public static boolean isAsciiPrintable(char ch) {
if(ch >= 32 && ch < 127)
{
return true;
}
else
//return false and do the stuff in calling method.
}
you can also modify your existing code to get the desired output as below,
String hex = "61647366616473000000";
StringBuilder output = new StringBuilder();
for (int i = 0; i < hex.length(); i += 2) {
String str = hex.substring(i, i + 2);
int decimal = Integer.parseInt(str, 16);
output.append((char) decimal);
}
System.out.println("YourText" + output.toString().replaceAll("\\p{C}", ""));
There are may be some invisible whitespace characters (like 0x0200B), which are part of \p{Zs} group which also contains whitespace. if you are trying to filter an input string that shouldn't contain any spaces, the string replaceAll("[\p{C}\p{Z}]", "") will work.