JavaScript进行UTF-8编码与解码

https://www.cnblogs.com/coloc/p/8111601.html

JavaScript本身可通过charCodeAt方法得到一个字符的Unicode编码,并通过fromCharCode方法将Unicode编码转换成对应字符。

但charCodeAt方法得到的应该是一个16位的整数,每个字符占用两字节。在网络上传输一般采用UTF-8编码,JavaScript本身没有提供此类方法。不过有一个简便的办法来实现UTF-8的编码与解码。

Web要求URL的查询字符串采用UTF-8编码,对于一些特殊字符或者中文等,会编码成多个字节,变成%加相应16进制码的形式。比如:汉字 中 将会被编码为%E4%B8%AD。

为此JavaScript提供了encodeURIComponent与decodeURIComponent方法组合来对查询字符串进行编码与解码。利用这一点,我们可以将encodeURIComponent方法编码后的字符串进行处理,最终得到对应的字节数组。代码如下:

function encodeUtf8(text) {
    const code = encodeURIComponent(text);
    const bytes = [];
    for (var i = 0; i < code.length; i++) {
        const c = code.charAt(i);
        if (c === '%') {
            const hex = code.charAt(i + 1) + code.charAt(i + 2);
            const hexVal = parseInt(hex, 16);
            bytes.push(hexVal);
            i += 2;
        } else bytes.push(c.charCodeAt(0));
    }
    return bytes;
}

这个方法的作用是得到某一个字符串对应UTF-8编码的字节序列,可在服务端语言,如C#中通过 System.Text.Encoding.UTF8.GetString(bytes) 方法将字节序列解码为相应的字符串。

而对应的,将以UTF-8编码的字节序列解码为String的JavaScript方法为:

function decodeUtf8(bytes) {
    var encoded = "";
    for (var i = 0; i < bytes.length; i++) {
        encoded += '%' + bytes[i].toString(16);
    }
    return decodeURIComponent(encoded);
}

该方法将每一字节都转换成%加16进制数字的表示形式,再通过decodeURIComponent方法解码,即可得到相应的字符串。使用示例如下:

var array = encodeUtf8('ab热cd!');
console.log(array);     // 打印 [97, 98, 231, 131, 173, 99, 100, 33] 
var content = decodeUtf8(array);
console.log(content);       // 打印 ab热cd!

对应的C#使用示例如下:

var bytes = System.Text.Encoding.UTF8.GetBytes("ab热cd!");
// 以下循环将打印 97 98 231 131 173 99 100 33
foreach (var b in bytes)
    Console.Write(b + " ");
Console.Write("\n");
var content = System.Text.Encoding.UTF8.GetString(bytes);
Console.WriteLine(content);  // 打印 ab热cd!

通过以上方法组合,即可通过websocket在前端与后端之间以二进制的形式交换数据,方便协议的制定。