计算【单个字符串】占多少【字节】的方法集

发表于 JS 分类,标签:

/**

 * @file  countStringByte.js

 * @version 1.0.1

 * @author wuwg  <wuwg@thunisoft.com>

 * @description   计算字节

 * @createTime  2019-08-13

 * @copyright thunisoft fd

 * @see [jsDoc中文文档]{@link  http://www.dba.cn/book/jsdoc/JSDOCKuaiBiaoQianBLOCKTAGS/CONSTRUCTS.html}

 */



export default {


    // 1.获取单字的字节长度

    getByteLength(value) {

        // 禁止在正则表达式中使用控制字符 :new RegExp('\x1f')

        const _pattern = /[^\x00-\xff]/g;  // eslint-disable-line

        // 非中文的正则判断

        return !value ? '0' : String(value)

            .replace(_pattern, '01').length;

    },


    // 2.获取单字的字节长度, 位计算

    getByteLength2(value) {

        const NUM = 0xff00;

        const NUM_2 = 2;

        // 非中文的正则判断

        return !value ? 0 : (String(value)

            .charCodeAt(0) & NUM) !== 0 ? NUM_2 : 1;

    },


    // 3.获取单字的字节长度, 判断 unicode

    getByteLength3(value) {

        if (!value) {

            return 0;

        }

        const _charCode = String(value)

            .charCodeAt(0);

        const NUM_2 = 2;

        const NUM_128 = 128;

        // 字节判断

        return (_charCode >= 0 && _charCode <= NUM_128) ? 1 : NUM_2;

    },


    // 4.获取单字的字节长度, 判断 unicode

    // 0x0001  1

    // 0x007e  126

    // 0xff60  65376

    // 0xff9f  65439

    getByteLength4(value) {

        if (!value) {

            return 0;

        }

        const _charCode = String(value)

            .charCodeAt(0);

        const NUM_1 = 1;

        const NUM_2 = 2;

        const NUM_126 = 0x007e;

        const NUM_65376 = 0xff60;

        const NUM_65439 = 0xff9f;

        return ((_charCode >= NUM_1 && _charCode <= NUM_126) || (_charCode >= NUM_65376 && _charCode <= NUM_65439)) ? 1 : NUM_2;

    },


    // 5.获取单字的字节长度, 判断 unicode

    getByteLength5(value) {

        if (!value) {

            return 0;

        }

        const _charCode = String(value)

            .charCodeAt(0);

        const NUM_2 = 2;

        const NUM_94 = 94;

        const NUM_127 = 127;

        return (_charCode > NUM_127 || _charCode === NUM_94) ? NUM_2 : 1;

    }

};


0 篇评论

发表我的评论