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.

hardartcore
  • 16,886
  • 12
  • 75
  • 101
  • 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? – Thomas Mueller Aug 03 '12 at 14:05
  • it's for some kind of security issue. i have to convert it to hex first – hardartcore Aug 03 '12 at 14:06
  • [Convert a String to hexadecimal in Java](http://stackoverflow.com/questions/923863/converting-a-string-to-hexadecimal-in-java) <---> [Convert Hex to ASCII in Java](http://www.mkyong.com/java/how-to-convert-hex-to-ascii-in-java/) – FoamyGuy Aug 03 '12 at 14:22

1 Answers1

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();
}
Sachin Chavan
  • 5,578
  • 5
  • 49
  • 75
hardartcore
  • 16,886
  • 12
  • 75
  • 101