js实现unicode码字符串与utf8字节数据互转

更新日期: 2019-01-29阅读: 2.7k标签: 

js的string变量存储字符串使用的是unicode编码,要保存时必须选择其他编码后进行传输,比如转成utf-8,utf-32等。存储到数据库中为utf-8编码,读取出来如何转换成正确的字符串就成了问题。现在给出解决方案,可以正确支持中文、emoji表情、英文混合的字符串编码互转。 

/**
 * Created by hdwang on 2019/1/28.
 */
var convertUtf8 = (function() {

    /**
     * unicode string to utf-8
     * @param text 字符串
     * @returns {*} utf-8编码
     */
    function toBytes(text) {
        var result = [], i = 0;
        text = encodeURI(text);
        while (i < text.length) {
            var c = text.charCodeAt(i++);

            // if it is a % sign, encode the following 2 bytes as a hex value
            if (c === 37) {
                result.push(parseInt(text.substr(i, 2), 16))
                i += 2;

                // otherwise, just the actual byte
            } else {
                result.push(c)
            }
        }

        return coerceArray(result);
    }


    /**
     * utf8 byte to unicode string
     * @param utf8Bytes
     * @returns {string}
     */
    function utf8ByteToUnicodeStr(utf8Bytes){
        var unicodeStr ="";
        for (var pos = 0; pos < utf8Bytes.length;){
            var flag= utf8Bytes[pos];
            var unicode = 0 ;
            if ((flag >>>7) === 0 ) {
                unicodeStr+= String.fromCharCode(utf8Bytes[pos]);
                pos += 1;

            } else if ((flag &0xFC) === 0xFC ){
                unicode = (utf8Bytes[pos] & 0x3) << 30;
                unicode |= (utf8Bytes[pos+1] & 0x3F) << 24;
                unicode |= (utf8Bytes[pos+2] & 0x3F) << 18;
                unicode |= (utf8Bytes[pos+3] & 0x3F) << 12;
                unicode |= (utf8Bytes[pos+4] & 0x3F) << 6;
                unicode |= (utf8Bytes[pos+5] & 0x3F);
                unicodeStr+= String.fromCodePoint(unicode) ;
                pos += 6;

            }else if ((flag &0xF8) === 0xF8 ){
                unicode = (utf8Bytes[pos] & 0x7) << 24;
                unicode |= (utf8Bytes[pos+1] & 0x3F) << 18;
                unicode |= (utf8Bytes[pos+2] & 0x3F) << 12;
                unicode |= (utf8Bytes[pos+3] & 0x3F) << 6;
                unicode |= (utf8Bytes[pos+4] & 0x3F);
                unicodeStr+= String.fromCodePoint(unicode) ;
                pos += 5;

            } else if ((flag &0xF0) === 0xF0 ){
                unicode = (utf8Bytes[pos] & 0xF) << 18;
                unicode |= (utf8Bytes[pos+1] & 0x3F) << 12;
                unicode |= (utf8Bytes[pos+2] & 0x3F) << 6;
                unicode |= (utf8Bytes[pos+3] & 0x3F);
                unicodeStr+= String.fromCodePoint(unicode) ;
                pos += 4;

            } else if ((flag &0xE0) === 0xE0 ){
                unicode = (utf8Bytes[pos] & 0x1F) << 12;;
                unicode |= (utf8Bytes[pos+1] & 0x3F) << 6;
                unicode |= (utf8Bytes[pos+2] & 0x3F);
                unicodeStr+= String.fromCharCode(unicode) ;
                pos += 3;

            } else if ((flag &0xC0) === 0xC0 ){ //110
                unicode = (utf8Bytes[pos] & 0x3F) << 6;
                unicode |= (utf8Bytes[pos+1] & 0x3F);
                unicodeStr+= String.fromCharCode(unicode) ;
                pos += 2;

            } else{
                unicodeStr+= String.fromCharCode(utf8Bytes[pos]);
                pos += 1;
            }
        }
        return unicodeStr;
    }



    function checkInt(value) {
        return (parseInt(value) === value);
    }

    function checkInts(arrayish) {
        if (!checkInt(arrayish.length)) { return false; }

        for (var i = 0; i < arrayish.length; i++) {
            if (!checkInt(arrayish[i]) || arrayish[i] < 0 || arrayish[i] > 255) {
                return false;
            }
        }

        return true;
    }

    function coerceArray(arg, copy) {

        // ArrayBuffer view
        if (arg.buffer && arg.name === 'Uint8Array') {

            if (copy) {
                if (arg.slice) {
                    arg = arg.slice();
                } else {
                    arg = Array.prototype.slice.call(arg);
                }
            }

            return arg;
        }

        // It's an array; check it is a valid representation of a byte
        if (Array.isArray(arg)) {
            if (!checkInts(arg)) {
                throw new Error('Array contains invalid value: ' + arg);
            }

            return new Uint8Array(arg);
        }

        // Something else, but behaves like an array (maybe a Buffer? Arguments?)
        if (checkInt(arg.length) && checkInts(arg)) {
            return new Uint8Array(arg);
        }

        throw new Error('unsupported array-like object');
    }

    return {
        toBytes: toBytes,
        fromBytes: utf8ByteToUnicodeStr
    }
})()


 针对emoji的字节字符,占两个unicode字符。使用String.fromCharCode也可以实现,需要进行两次fromCharCode,没有fromPointCode方便。下面展示了utf-8的4字节转换为unicode(utf-16)的过程。

//高char10位[一个unicode字符] (2+6+2=10)
unicode =   ((utf8Bytes[pos] & 0x3)) << 8 |((utf8Bytes[pos+1] & 0x3f) << 2) |((utf8Bytes[pos+2] >> 4) & 0x03);

//减去‭1F600‬中的1,这里减去6个0即可,低位char已经占据10位
unicode = unicode - parseInt('1000000',2)

//加上utf-16高char的标识符
unicode =  0xD800 + unicode;
console.log(unicode);
unicodeStr +=  String.fromCharCode(unicode);

//低char10位[一个unicode字符](4+6)
unicode =  ((utf8Bytes[pos+2] & 0x0F) << 6) | (utf8Bytes[pos+3] & 0x3F);
//加上utf-16低char的标识符
unicode = 0xDC00 + unicode;
console.log(unicode);
unicodeStr+=  String.fromCharCode(unicode);
pos += 4;


来自:https://www.cnblogs.com/hdwang/archive/2019/01/28/10331344.html


链接: https://www.fly63.com/article/detial/1899

js之汉字与Unicode码的相互转化

js unicode是以十六进制代码外加开头\\u表示的字符串。本文将讲解通过js实现unicode转化为汉字的方法,实现汉字转Unicode码。

中文utf 8占几个byte——UTF-8中一个汉需要占用三个字节

中文汉字在utf-8中到底占几个字节,一般是3个字节,最常见的编码方式是1110xxxx 10xxxxxx 10xxxxxx。

终于搞懂了回车与换行的区别

关于换行和回车其实平时我们不太在意,所以关于两者的区别也不太清楚,在平时开发时可能会遇到一些文件处理的问题,放到不同的操作系统上出现各种坑。那么回车和换行到底有哪些区别呢?

ascii码表/ascii编码_最全的ASCII码对照表

ASCII是基于拉丁字母的一套电脑编码系统。这篇文章主要介绍: 什么是ASCII、ASCII简介、ASCII码产生、ASCII码的算法、汉字编码、ASCII码图、最全的ASCII码对照表

js编码方式详解

escape(), encodeURI()和encodeURIComponent()是在Javascript中用于编码字符串的三个常用的方法,而他们之间的异同却困扰了很多的Javascript初学者,今天我就在这里对这三个方法详细地分析与比较一下。

Unicode字符集和UTF8编码编码的前世今生

很久很久以前,有一群人,他们决定用8个可以开合的晶体管来组合成不同的状态,以表示世界上的万物。他们看到8个开关状态是好的,于是他们把这称为”字节“。再后来,他们又做了一些可以处理这些字节的机器,机器开动了

web开发中URL编码

因为当字符串数据以url的形式传递给web服务器时,字符串中是不允许出现空格和特殊字符的。也就是说,url的参数传递的时候,需要遵循一定的url规范才能正确的传送。通常如果一样东西需要编码,说明这样东西并不适合传输。

字符集和编码

字符集 Charset :是一个系统支持的所有字符的集合,包括各国家文字、标点符号、图形符号、数字等。编码是信息从一种形式或格式转换为另一种形式的过程,也称为计算机编程语言的代码简称编码。

带你了解字符编码的前世今生

世界第一台计算机诞生了。计算机由硬件和系统软件组成,它最基本的功能就是存储、表示与处理信息。通俗地说,信息其实就是由各种各样的字符组成,比如英文字母、汉字以及其他国家的语言等。

常见Web报错code码

1xx-信息提示:这些状态代码表示临时的响应。客户端在收到常规响应之前,应准备接收一个或多个1xx响应。2xx-成功:这类状态代码表明服务器成功地接受了客户端请求。

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!