当前位置:网站首页>Get string byte size

Get string byte size

2022-06-21 05:51:00 Pig in August

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <script>
        function getSize(str) {
            const bytes = unescape(encodeURIComponent(str)).length; //  Get bytes 
            const bytes1 = new Blob([str]).size; //  Get bytes 
            console.log(" Byte size ...", bytes, bytes1);
            const size = convert("B", bytes);
            return `${str}  Character size :${size}`;
        }

        function convert(unit, bytes) {
            const units = ["B", "KB", "MB", "GB", "TB"];
            const i = units.indexOf(unit);
            const size = (bytes / pow1024(i)).toFixed(2); //  Bytes to other units 
            return `${size} ${units[i]}`;
        }

        //  Find the power 
        function pow1024(num) {
            return Math.pow(1024, num);
        }

        // 1 Bytes are 8 Binary bits (8 Binary bits make up 1 Bytes ), namely 1Byte=8bit( A combination of eight bits , share 256 Circuit states ).
        // 1 A digital =1 English letters ( character )=1 byte (Byte), That is, a standard English letter is a byte , It has 8 A bit (bit),( Such as A by 10D, use 00001010 To express ,8 Binary bits ).1 The Chinese characters =2 Bytes , That is, a standard Chinese character has 2 Bytes ,8 individual bit A byte , That is to say, in the computer 1 A Chinese character should be used 16 individual bit To express . In addition, Chinese punctuation marks account for 2 Bytes , English Punctuations (,.?!%&+-*/), Occupy 1 Bytes , Chinese Ellipsis (……) Hekuo ( Broken fold ) Number (——) Each account 4 Bytes .  The size of a file is actually the number of bytes the file content actually has , It uses Byte Is the unit of measurement , As long as the file content and format do not change , The file size will not change .

        console.log(getSize("aaa"));
        console.log(getSize(123));
        console.log(getSize(" Blue forget the machine "));

        //  Reference documents :
        // 1. https://segmentfault.com/q/1010000007847667
        // 2. https://blog.csdn.net/qq_23994787/article/details/86609659
        // 3. https://aixiaodou.blog.csdn.net/article/details/108885082?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-108885082-blog-106854329.pc_relevant_downloadblacklistv1&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1-108885082-blog-106854329.pc_relevant_downloadblacklistv1&utm_relevant_index=1
    </script>
</body>

</html>
原网站

版权声明
本文为[Pig in August]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210546072560.html