1

Working on web application which accepts all UTF-8 character's including greek characters following are strings that i want to convert to hex.
Following are different language string which are not working in my current code

ЫЙБПАРО Εγκυκλοπαίδεια éaös Größe Größe

Following are hex conversions by javascript function mentioned below

42b41941141f41042041e 3953b33ba3c53ba3bb3bf3c03b13af3b43b53b93b1 e961f673 4772c3192c2b6c3192c217865 4772f6df65

Javascript function to convert above string to hex

function encode(string) {
     var str= "";
        var length = string.length;        
        for (var i = 0; i < length; i++){
            str+= string.charCodeAt(i).toString(16);
            }
        return str;
}

Here it is not giving any error to convert but at java side I'm unable to parse such string used following java code to convert hex

public String HexToString(String hex){

          StringBuilder finalString = new StringBuilder();
          StringBuilder tempString = new StringBuilder();

          for( int i=0; i<hex.length()-1; i+=2 ){                
              String output = hex.substring(i, (i + 2));             
              int decimal = Integer.parseInt(output, 16);            
              finalString.append((char)decimal);     
              tempString.append(decimal);
          }
        return finalString.toString();
    }

It throws error while parsing above hex string giving parse exception. Suggest me the solution

1 Answer 1

1

Javascript works with 16-bit unicode characters, therefore charCodeAt might return any number between 0 and 65535. When you encode it to hex you get strings from 1 to 4 chars, and if you simply concatenate these, there's no way for the other party to find out what characters have been encoded.

You can work around this by adding delimiters to your encoded string:

function encode(string) {
     return string.split("").map(function(c) {
        return c.charCodeAt(0).toString(16);
     }).join('-');
}

alert(encode('größe Εγκυκλοπαίδεια 维'))

2
  • gr8 Idea to encode string at javascript side. Similarly i'm facing issue at java side. How do parse/convert encoded string.
    – Rahul P
    Commented Jan 22, 2015 at 11:23
  • @RahulP: I don't know Java, but I guess it has a split function?
    – georg
    Commented Jan 22, 2015 at 11:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.