Implement Chinese UTF-8 encoding with JavaScript

zhaozj2021-02-16  78

// -------- Convert Chinese characters into UTF8 codes ---------------------- //

Function EncodeUTF8 (S1)

{

Var s = escape (s1);

Var sa = s.split ("%");

Var Retv = ""

IF (SA [0]! = "")

{

RETV = SA [0];

}

FOR (var i = 1; i

{

IF (sa [i] .substring (0, 1) == "u")

{

RETV = HEX2UTF8 (STR2HEX (SA [i] .substring (1, 5)));

}

Else Retv = "%" SA [i];

}

Return Retv;

}

Function str2hex (s)

{

VAR C = ""

VAR N;

VAR SS = "0123456789AbcDef";

VAR DIGS = ""

FOR (var i = 0; i

{

C = S.Charat (i);

n = s.indexof (c);

DIGS = DEC2DIG (EVAL (N));

}

// Return Value;

Return DIGS;

}

Function dec2dig (N1)

{

Var s = ""

VAR N2 = 0;

FOR (var i = 0; i <4; i )

{

N2 = math.pow (2, 3 - i);

IF (n1> = n2)

{

S = '1';

N1 = n1 - n2;

}

Else

S = '0';

}

Return S;

}

Function Dig2DEC (s)

{

Var Retv = 0;

IF (s.length == 4)

{

FOR (var i = 0; i <4; i )

{

RETV = evAl (S.Charat (i)) * Math.Pow (2, 3 - i);

}

Return Retv;

}

Return -1;

}

Function HEX2UTF8 (S)

{

Var retts = "";

VAR TEMPS = ""

Var ss = ""

IF (s.length == 16)

{

Temps = "1110" s.substring (0, 4);

Temps = "10" S.SUBSTRING (4, 10);

Temps = "10" s.substring (10,16);

VAR SSS = "0123456789Abcdef";

FOR (var i = 0; i <3; i )

{

RETS = "%";

SS = Temps.Substring (i * 8, (Eval (i) 1) * 8);

RES = SSS.CHARAT (DIG2DEC (ss.substring (0, 4)))); RETS = SSS.CHARAT (DIG2DEC (Ss.Substring (4, 8)))

}

Return RETS;

}

""; "

}

转载请注明原文地址:https://www.9cbs.com/read-14095.html

New Post(0)