2012年2月29日 星期三

javascript string to Hex

ActionScript Code:
function encodeToHex(str){
    var r="";
    var e=str.length;
    var c=0;
    var h;
    while(c<e){
        h=str.charCodeAt(c++).toString(16);
        while(h.length<3) h="0"+h;
        r+=h;
    }
    return r;
}
function decodeFromHex(str){
 var r="";
 var e=str.length;
 var s=0;
 while(e>1){

 r=r+String.fromCharCode("0x"+str.substring(s,s+2));
 s=s+2;
 e=e-2;
 }

return r;
}

str = "hello";
trace("Original: "+str);
str = encodeToHex(str);
trace("Encode: "+str);
str = decodeFromHex(str);
trace("Decode: "+str);
output Code:
Original: hello
Encode: 06806506c06c06f
Decode: hello

沒有留言:

張貼留言