Search code examples
javascriptutf-8hex

Encode String to HEX


i have my function to convert string to hex:

function encode(str){
    str = encodeURIComponent(str).split('%').join('');
    return str.toLowerCase();
}

example:

守护村子

alert(encode('守护村子'));

the output would be:

e5ae88e68aa4e69d91e5ad90

It works on Chinese characters. But when i do it with English letters

alert(encode('Hello World'));

it outputs:

hello20world

I have tried this for converting string to hex:

function String2Hex(tmp) {
    var str = '';
    for(var i = 0; i < tmp.length; i++) {
        str += tmp[i].charCodeAt(0).toString(16);
    }
    return str;
}

then tried it on the Chinese characters above, but it outputs the UTF-8 HEX:

5b8862a467515b50

not the ANSI Hex:

e5ae88e68aa4e69d91e5ad90

I also have searched converting UFT8 to ANSI but no luck. Anyone could help me? Thanks!


Solution

  • I solved it by downloading utf8.js

    https://github.com/mathiasbynens/utf8.js

    then using the String2Hex function from above:

    alert(String2Hex(utf8.encode('守护村子')));
    

    It gives me the output I want:

    e5ae88e68aa4e69d91e5ad90