Reputation: 1810
Need to decode hex code in array when accessed by index.User should enter array index and get decoded hex in array as output.
import java.util.Scanner;
class Find {
static String[] data={ " \\x6C\\x65\\x6E\\x67\\x74\\x68",
"\\x73\\x68\\x69\\x66\\x74"
//....etc upto 850 index
};
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number");
int s = in.nextInt();
String decodeinput=data[s];
// need to add some code here
//to decode hex and store to a string decodeoutput to print it
String decodeoutput=......
System.out.println();
}
}
How about using...
String hexString ="some hex string";
byte[] bytes = Hex.decodeHex(hexString .toCharArray());
System.out.println(new String(bytes, "UTF-8"));
Upvotes: 0
Views: 960
Reputation: 757
Append the following code after getting the value of s from user. Imp: Please use camelCase convention for naming variables as pointed out above. I have just gone ahead and used the same names as you have for your convinience for now.
if (s>= 0 && s < data.length) {
String decodeinput = data[s].trim();
StringBuilder decodeoutput = new StringBuilder();
for (int i = 2; i < decodeinput.length() - 1; i += 4) {
// Extract the hex values in pairs
String temp = decodeinput.substring(i, (i + 2));
// convert hex to decimal equivalent and then convert it to character
decodeoutput.append((char) Integer.parseInt(temp, 16));
}
System.out.println("ASCII equivalent : " + decodeoutput.toString());
}
OR, just complete what you were doing:
/* import java.io.UnsupportedEncodingException;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex; //present in commons-codec-1.7.jar
*/
if (s>= 0 && s < data.length) {
String hexString =data[s].trim();
hexString = hexString.replace("\\x", "");
byte[] bytes;
try {
bytes = Hex.decodeHex(hexString.toCharArray());
System.out.println("ASCII equivalent : " + new String(bytes, "UTF-8"));
} catch (DecoderException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
Upvotes: 1