hardartcore
hardartcore

Reputation: 17037

Android Java create hex string and convert it to byte array and back

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.

Upvotes: 2

Views: 10867

Answers (1)

hardartcore
hardartcore

Reputation: 17037

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();
}

Upvotes: 5

Related Questions