Android Java create hex string and convert it to byte array and back
10,334
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();
}
Related videos on Youtube
Author by
hardartcore
Updated on May 25, 2022Comments
-
hardartcore almost 2 years
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.
-
Thomas Mueller over 11 yearsDo 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?
-
hardartcore over 11 yearsit's for some kind of security issue. i have to convert it to hex first
-
FoamyGuy over 11 years
-