Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python to Java code conversion

Tags:

java

python

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);
}
like image 361
Kyle93 Avatar asked Nov 26 '13 16:11

Kyle93


1 Answers

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.

  1. 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.

  2. 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) + " ";
    }
    
  3. Lose the toText method. At this point you have the string you wanted, so that method doesn't really do anything anymore.

like image 175
Ian McLaird Avatar answered Oct 04 '22 20:10

Ian McLaird