-1

How to can i convert hex value to string ? i get this weird result by using the following method.

for example :

String result = DB_record.convertHexToString(PASSWORD); 
// c53255317bb11707d0f614696b3ce6f221d0e2f2 hex value;
System.err.println("result==="+result);

Java

 public String convertHexToString(String hex){

  StringBuilder sb = new StringBuilder();
  StringBuilder temp = new StringBuilder();
  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);
  }

  return sb.toString();
 }

output

enter image description here

Ling Zhong
  • 1,744
  • 14
  • 24
user3835327
  • 1,194
  • 1
  • 14
  • 44
  • 2
    Possible duplicate of [How to convert hex string to java string](http://stackoverflow.com/questions/13990941/how-to-convert-hex-string-to-java-string) – Tim Biegeleisen Oct 19 '15 at 06:04
  • The example you are giving (in @Michal 's post's comments) suggests that you are actually encrypting the text before saving in DB. You will need to decrypt it then to get the original text. How can hex to string help? And, if this is the case, the question is too unclear to be answered. – vish4071 Oct 19 '15 at 06:50

2 Answers2

0

Problem lays here sb.append((char)decimal);

this is not a correct way, how to convert int to String.

try this

sb.append(Integer.toString(decimal));
Michal Krasny
  • 5,434
  • 7
  • 36
  • 64
  • Hi @Michal, thanks for reply. But the result is not the result when i encrypted. `c53255317bb11707d0f614696b3ce6f221d0e2f2` original text is `qwe123` , the result i got is `197508549123177237208246201051076023024233208226242` after using the solution u provided. – user3835327 Oct 19 '15 at 06:24
  • Of course. What you are doing is decoding from HEX do DEC - one number to another number. I think, that what you want to do is to get the original text. Assuming "c53255317bb11707d0f614696b3ce6f221d0e2f2" is hash, then what you want to do is mathematically impossible. Read more here https://en.wikipedia.org/wiki/Cryptographic_hash_function. You might also be interested in differences between hashing and encryption, I will leave this up to you :) – Michal Krasny Oct 19 '15 at 06:30
0
 byte[] bytes = DatatypeConverter.parseHexBinary(hexString);
      String result= new String(bytes, encoding);
Akhil Jayakumar
  • 2,262
  • 14
  • 25
  • While this may theoretically answer the question, it's not really a good answer, since it doesn't teach the OP. Instead it gives an alternative solution without explanation. This will usually lead to OP not learning, and coming back for asking a new question when a similar problem occurs. Would you mind adding some explanation? – Vogel612 Oct 19 '15 at 09:08