JavaScript实现UTF-8编解码


当前第2页 返回上一页

以下是js实现代码,首先是编码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

function utf8Encode(inputStr) {

  var outputStr = "";

   

  for(var i = 0; i < inputStr.length; i++) {

    var temp = inputStr.charCodeAt(i);

     

    //0xxxxxxx

    if(temp < 128) {

      outputStr += String.fromCharCode(temp);

    }

    //110xxxxx 10xxxxxx

    else if(temp < 2048) {

      outputStr += String.fromCharCode((temp >> 6) | 192);

      outputStr += String.fromCharCode((temp & 63) | 128);

    }

    //1110xxxx 10xxxxxx 10xxxxxx

    else if(temp < 65536) {

      outputStr += String.fromCharCode((temp >> 12) | 224);

      outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);

      outputStr += String.fromCharCode((temp & 63) | 128);

    }

    //11110xxx 10xxxxxx 10xxxxxx 10xxxxxx

    else {

      outputStr += String.fromCharCode((temp >> 18) | 240);

      outputStr += String.fromCharCode(((temp >> 12) & 63) | 128);

      outputStr += String.fromCharCode(((temp >> 6) & 63) | 128);

      outputStr += String.fromCharCode((temp & 63) | 128);

    }

  }

   

  return outputStr;

}

下面是解码

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

function utf8Decode(inputStr) {

  var outputStr = "";

  var code1, code2, code3, code4;

   

  for(var i = 0; i < inputStr.length; i++) {

    code1 = inputStr.charCodeAt(i);

     

    if(code1 < 128) {

      outputStr += String.fromCharCode(code1);

    }

    else if(code1 < 224) {

      code2 = inputStr.charCodeAt(++i);

      outputStr += String.fromCharCode(((code1 & 31) << 6) | (code2 & 63));

    }

    else if(code1 < 240) {

      code2 = inputStr.charCodeAt(++i);

      code3 = inputStr.charCodeAt(++i);

      outputStr += String.fromCharCode(((code1 & 15) << 12) | ((code2 & 63) << 6) | (code3 & 63));

    }

    else {

      code2 = inputStr.charCodeAt(++i);

      code3 = inputStr.charCodeAt(++i);

      code4 = inputStr.charCodeAt(++i);

      outputStr += String.fromCharCode(((code1 & 7) << 18) | ((code2 & 63) << 12) |((code3 & 63) << 6) | (code2 & 63));

    }

  }

   

  return outputStr;

}

以上!

相关免费学习推荐:javascript(视频)

以上就是JavaScript实现UTF-8编解码的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

html、css和js的注释规范用法有哪些

javascript如何设置select

d3js怎么样

js中isnan和number.isnan的区别是什么

jquery javascript ajax区别是什么

javascript如何添加节点

javascript如何添加随机数

js中怎么换行

es6 filter() 数组过滤的方法小结(附代码)

详解javascript中的generator生成器

更多相关阅读请进入《javascript》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...