Click here to Skip to main content
15,877,939 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Hi,
I have a problem in converting hex string to ascii string in java, i.e. if the user enters "06", my application should convert it to "0x30 0x36" and pass this value to a byte array. Please help me out....
Posted
Comments
Sergey Alexandrovich Kryukov 7-Jul-15 11:10am    
What have you tried so far?
—SA
Richard MacCutchan 7-Jul-15 13:12pm    
If the user enters "06" you already have the two hex characters x30 and x36. You need to understand how input is presented in computer programs.

1 solution

It does not mean "Hex string to ASCII". Java strings are not ASCII, they use Unicode. ASCII codes is what you expect from the user, in the form of numeric string, no matter hexadecimal or decimal, and on output you need characters.
Also, you need to validate the user input, to allow only (printable) characters, or you should present non-printable characters in some other way.

First, you need to parse string entered by the user to the numeric value, a byte, for example,
Java
String input;
//...
byte value = Byte.parseByte(input, 16);
http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte(java.lang.String)[^],
http://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html#parseByte(java.lang.String,%20int)[^].

Note that, with the second function, you can choose the radix of expected input. Again, parsing can fail. When you get a value, you just need to typecast it to a character:
Java
char output = (char)value;

Again, the character obtained might be not printable; so validate the value and decide what to do with that.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900