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

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;

以上所述是小编给大家介绍的js实现unicode码字符串与utf8字节数据互转详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • JS实现unicode和UTF-8之间的互相转换互转

    有一设备,为短信网关.需将PC送过来的UTF-8转换成UNICODE才能将内容通过短信发送出去,同样,接收到的短信为unicode编码,也许转换成UTF-8才能在PC端软件显示出来.程序很简单,只是走了不少弯路: //unicode为1个接收数据,串口收到的字符编码放在该数组中 function UnicodeToUtf8(unicode) { var uchar; var utf8str = ""; var i; for(i=0; i<unicode.length;i+=2){

  • JS实现汉字与Unicode码相互转换的方法详解

    本文实例讲述了JS实现汉字与Unicode码相互转换的方法.分享给大家供大家参考,具体如下: js文件中,有些变量的值可能会含有汉字,画面引入js以后,有可能会因为字符集的原因,把里面的汉字都变成乱码.后来发现网上的一些js里会把变量中的汉字都表示成"\u"开头的16进制编码,这样应该可以解决上面的问题. 最近有时间在网上查找了一下实现方式,一种比较大众化的: function tounicode(data) { if(data == '') return '请输入汉字'; var s

  • JS将unicode码转中文方法

    原理,将unicode的 \u 先转为 %u,然后使用unescape方法转换为中文. <script type="text/javascript"> var str = "\u7434\u5fc3\u5251\u9b44\u4eca\u4f55\u5728\uff0c\u6c38\u591c\u521d\u6657\u51dd\u78a7\u5929\u3002"; document.write(unescape(str.replace(/\\u/g,

  • JS实现的Unicode编码转换操作示例

    本文实例讲述了JS实现的Unicode编码转换操作.分享给大家供大家参考,具体如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Unicode编码转换</title> </head> <body> <script> /* *js Unicode编码转换 */ va

  • js字符串与Unicode编码互相转换

    '好'.charCodeAt(0).toString(16) "597d" 这段代码的意思是,把字符'好'转化成Unicode编码, 看看charCodeAt()是怎么个意思 charCodeAt() 方法可返回指定位置的字符的 Unicode 编码.这个返回值是 0 - 65535 之间的整数. 等于就是'charCodeAt()'里面的这个参数是指定位置的单个字符, '好哦'.charCodeAt(0).toString(16) "597d" '好哦'.char

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

    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 * @p

  • Go源码字符串规范检查lint工具strchecker使用详解

    目录 1.背景 2.strchecker介绍 3.结论 1.背景 在大型项目开发过程中,经常会遇到打印大量日志,输出信息和在源码中写注释的情况.对于软件开发来说,我们一般都是打印输出英文的日志(主要考虑软件在各种环境下的兼容性,如果打印中文日志可能会出现乱码,另外英文日志更容易搜索,更容易后续做国际化),但是对于我们中国人来说,很容易就把中文全角的中文标点符号一不注意就写到日志中了.不过源码中的注释因为是完全面向开发者的,不会面向客户,所以如果研发团队全是中国人,那么代码注释用中文就更有效率.

  • JS实现对中文字符串进行utf-8的Base64编码的方法(使其与Java编码相同)

    本文实例讲述了JS实现对中文字符串进行utf-8的Base64编码的方法.分享给大家供大家参考,具体如下: 要进行编码的字符串:"select 用户名 from 用户" 使用JAVA进行编码,Java程序: String sql = "select 用户名 from 用户"; String encodeStr = new String(Base64.encode(sql.getBytes("UTF-8"))); // 编码 System.out.

  • JS字符串与二进制的相互转化实例代码详解

    JS字符串与二进制的相互转化的方法,具体代码如下所示: //字符串转ascii码,用charCodeAt(); //ascii码转字符串,用fromCharCode(); var str = "A"; var code = str.charCodeAt(); var str2 = String.fromCharCode(code); 十进制转二进制 var a = "i"; console.log(a.charCodeAt()); //105 console.log

  • 基于js 字符串indexof与search方法的区别(详解)

    1.indexof方法 indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置. 语法: 注意:有可选的参数(即设置开始的检索位置). 2.search方法 search() 方法用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串. 注意:search方法可以根据正则表达式查找指定字符串(可以忽略大小写,并且不执行全局检索),同时没有可选参数(即设置开始的检索位置). 以上这篇基于js 字符串indexof与search方法的区别(详解)就是小编分享给大家的全部

  • python不相等的两个字符串的 if 条件判断为True详解

    今天遇到一个非常基础的问题,结果搞了好久好久.....赶快写一篇博客记录一下: 本来两个不一样的字符串,在if 的条件判断中被判定为True,下面是错误的代码: test_str = 'happy' if test_str == 'good' or 'happy': #这样if判断永远是True,写法错误 print('aa') else: print('bbbb') 这是正确的代码: test_str = 'happy' if test_str == 'good' or test_str ==

  • Python字符串和字典相关操作的实例详解

    Python字符串和字典相关操作的实例详解 字符串操作: 字符串的 % 格式化操作: str = "Hello,%s.%s enough for ya ?" values = ('world','hot') print str % values 输出结果: Hello,world.hot enough for ya ? 模板字符串: #coding=utf-8 from string import Template ## 单个变量替换 s1 = Template('$x, glorio

  • C++ 中字符串操作--宽窄字符转换的实例详解

    C++ 中字符串操作--宽窄字符转换的实例详解 MultiByteToWideChar int MultiByteToWideChar( _In_ UINT CodePage, _In_ DWORD dwFlags, _In_ LPCSTR lpMultiByteStr, _In_ int cbMultiByte, _Out_opt_ LPWSTR lpWideCharStr, _In_ int cchWideChar ); 参数描述: CodePage:常用CP_ACP.CP_UTF8 dwF

  • CentOS 6.6 源码编译安装MySQL 5.7.18教程详解

    一.添加用户和组 1.添加mysql用户组 # groupadd mysql 2.添加mysql用户 # useradd -g mysql -s /bin/nologin mysql -M 二.查看系统中是否安装mysql,如果安装需要卸载 # rpm -qa | grep mysql mysql-libs-5.1.73-3.el6_5.x86_64 # rpm -e mysql-libs-5.1.73-3.el6_5.x86_64 --nodeps 三.安装所需依赖包 # yum -y ins

  • Java 判断字符串中是否包含中文的实例详解

    Java 判断字符串中是否包含中文的实例详解 Java判断一个字符串是否有中文是利用Unicode编码来判断,因为中文的编码区间为:0x4e00--0x9fbb, 不过通用区间来判断中文也不非常精确,因为有些中文的标点符号利用区间判断会得到错误的结果.而且利用区间判断中文效率也并不高,例如:str.substring(i, i + 1).matches("[\\一-\\?]+"),就需要遍历整个字符串,如果字符串太长效率非常低,而且判断标点还会错误.这里提高 一个高效准确的判断方法,使

随机推荐