2

I want to achieve something in my android application. I need to create a HEX representation of a String variable in my class and to convert it to byte array. Something like this :

String hardcodedStr = "SimpleText";
String hexStr = someFuncForConvert2HEX(hardcodedStr); // this should be the HEX string
byte[] hexStr2BArray = hexStr.getBytes();

and after that I want to be able to convert this hexStr2BArray to String and get it's value. Something like this :

String hexStr = new String(hexStr2BArray, "UTF-8");
String firstStr = someFuncConvertHEX2Str(hexStr); // the result must be : "SimpleText"

Any suggestions/advices how can I achieve this. And another thing, I should be able to convert that hexString and gets it's real value in any other platform...like Windows, Mac, IOS.

3
  • Do you really need it to be hex (characters 0..9 and a..f), why can't the byte array just be the UTF-8 encoded string? Commented Aug 3, 2012 at 14:05
  • it's for some kind of security issue. i have to convert it to hex first Commented Aug 3, 2012 at 14:06
  • Convert a String to hexadecimal in Java <---> Convert Hex to ASCII in Java Commented Aug 3, 2012 at 14:22

1 Answer 1

5

Here are two functions which I am using thanks to Tim's comment. Hope it helps to anyone who need it.

public String convertStringToHex(String str){

  char[] chars = str.toCharArray();

  StringBuffer hex = new StringBuffer();
  for(int i = 0; i < chars.length; i++){
    hex.append(Integer.toHexString((int)chars[i]));
  }

  return hex.toString();
}

public String convertHexToString(String hex){

  StringBuilder sb = new StringBuilder();
  StringBuilder temp = new StringBuilder();

  //49204c6f7665204a617661 split into two characters 49, 20, 4c...
  for( int i=0; i<hex.length()-1; i+=2 ){

      //grab the hex in pairs
      String output = hex.substring(i, (i + 2));
      //convert hex to decimal
      int decimal = Integer.parseInt(output, 16);
      //convert the decimal to character
      sb.append((char)decimal);

      temp.append(decimal);
  }
  System.out.println("Decimal : " + temp.toString());

  return sb.toString();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.