Could anyone give me a hand converting this Python script to Java?
This is the code
theHex = input("Hex: ").split()
theShift = int(input("Shift: "))
result = ""
for i in range (len(theHex)):
result += (hex((int(theHex[i],16) + theShift))).split('x')[1] + " "
print(result)
Here is what I've got
System.out.print("Please enter the hex: ");
String theHex = BIO.getString();
String[] theHexArray = theHex.split(" ");
System.out.print("Please enter the value to shift by: ");
int theShift = BIO.getInt();
String result[] = null;
for( int i = 0 ; i < theHex.length() ; i++ ){
//result += (hex((int(theHex[i],16) + theShift))).split('x')[1] + " "
}
toText(result[]);
BIO is a class I have to collect Strings and Ints. Think of it as basically a scanner.
Could anyone help me translate the last line?
EDIT Here is the toText method
public static void toText(String theHexArray[]){
String theHex = "";
for(int i = 0 ; i < theHexArray.length ; i++ ){
theHex += theHexArray[i];
}
StringBuilder output = new StringBuilder();
try{
for (int i = 0; i < theHex.length(); i+=2){
String str = theHex.substring(i, i+2);
output.append((char)Integer.parseInt(str, 16));
}
}catch(Exception e){
System.out.println("ERROR");
}
System.out.println(output);
}
I suspect you're making this rather more work for yourself than you really need to, but here goes.
If you're going to go for a line-by-line port, then do that.
Don't declare result as an array of strings. That'll just give you a headache. Make it either a StringBuilder
or a plain String
as I do here (StringBuilder
will be more efficient, admittedly, but this is probably easier to understand). This is also more similar to the python code you already have.
Understand what your python code is doing. It's taking a string in hex format, parsing it to an integer, adding a value (theShift
), converting back into hex, and then getting just the numeric part of the string (without the leading 0x
). So in Java, that loop goes like this. (NOTE: in Java Integer.toString(x, 16)
does not print the leading 0x
, so we don't need to chop it off).
String result = "";
for (String thisHex : theHexArray) {
result += Integer.toString(Integer.parseInt(thisHex, 16) + theShift, 16) + " ";
}
Lose the toText
method. At this point you have the string you wanted, so that method doesn't really do anything anymore.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With