search
HomeWeb Front-endJS TutorialJavaScript front-end development to implement binary read and write operations_javascript skills

For an introduction to implementing binary read and write operations in JavaScript front-end development, please see the following detailed explanation. This article is very detailed and has reference value.

Due to various reasons, binaries cannot be operated in the browser like nodejs.

Recently wrote a helper class to operate reading and writing binary on the browser side

!function (entrance) {
  "use strict";
  if ("object" === typeof exports && "undefined" !== typeof module) {
    module.exports = entrance();
  } else if ("function" === typeof define && define.amd) {
    define([], entrance());
  } else {
    var f;
    if ("undefined" !== typeof window) {
      f = window;
    } else {
      throw new Error('wrong execution environment');
    }
    f.TinyStream = entrance();
  }
}(function () {
  var binaryPot = {
    /**
     * 初始化字节流,把-128至128的区间改为0-256的区间.便于计算
     * @param {Array} array 字节流数组
     * @return {Array} 转化好的字节流数组
     */
    init: function (array) {
      for (var i = 0; i < array.length; i++) {
        array[i] *= 1;
        if (array[i] < 0) {
          array[i] += 256
        }
        if(array[i]>255){
          throw new Error('不合法字节流')
        }
      }
      return array;
    },
    /**
     * 把一段字符串按照utf8编码写到缓冲区中
     * @param {String} str 将要写入缓冲区的字符串
     * @param {Boolean} isGetBytes 是否只得到内容字节(不包括最开始的两位占位字节)
     * @returns {Array} 字节流
     */
    writeUTF: function (str, isGetBytes) {
      var back = [],
        byteSize = 0;
      for (var i = 0; i < str.length; i++) {
        var code = str.charCodeAt(i);
        if (code >= 0 && code <= 127) {
          byteSize += 1;
          back.push(code);
        } else if (code >= 128 && code <= 2047) {
          byteSize += 2;
          back.push((192 | (31 & (code >> 6))));
          back.push((128 | (63 & code)))
        } else if (code >= 2048 && code <= 65535) {
          byteSize += 3;
          back.push((224 | (15 & (code >> 12))));
          back.push((128 | (63 & (code >> 6))));
          back.push((128 | (63 & code)))
        }
      }
      for (i = 0; i < back.length; i++) {
        if (back[i] > 255) {
          back[i] &= 255
        }
      }
      if (isGetBytes) {
        return back
      }
      if (byteSize <= 255) {
        return [0, byteSize].concat(back);
      } else {
        return [byteSize >> 8, byteSize & 255].concat(back);
      }
    },
    /**
     * 把一串字节流按照utf8编码读取出来
     * @param arr 字节流
     * @returns {String} 读取出来的字符串
     */
    readUTF: function (arr) {
      if (Object.prototype.toString.call(arr) == "[object String]") {
        return arr;
      }
      var UTF = "",
        _arr = this.init(arr);
      for (var i = 0; i < _arr.length; i++) {
        var one = _arr[i].toString(2),
          v = one.match(/^1+&#63;(&#63;=0)/);
        if (v && one.length == 8) {
          var bytesLength = v[0].length,
            store = _arr[i].toString(2).slice(7 - bytesLength);
          for (var st = 1; st < bytesLength; st++) {
            store += _arr[st + i].toString(2).slice(2)
          }
          UTF += String.fromCharCode(parseInt(store, 2));
          i += bytesLength - 1
        } else {
          UTF += String.fromCharCode(_arr[i])
        }
      }
      return UTF
    },
    /**
     * 转换成Stream对象
     * @param x
     * @returns {Stream}
     */
    convertStream: function (x) {
      if (x instanceof Stream) {
        return x
      } else {
        return new Stream(x)
      }
    },
    /**
     * 把一段字符串转为mqtt格式
     * @param str
     * @returns {*|Array}
     */
    toMQttString: function (str) {
      return this.writeUTF(str)
    }
  };
  /**
   * 读取指定长度的字节流到指定数组中
   * @param {Stream} m Stream实例
   * @param {number} i 读取的长度
   * @param {Array} a 存入的数组
   * @returns {Array} 存入的数组
   */
  function baseRead(m, i, a) {
    var t = a &#63; a : [];
    for (var start = 0; start < i; start++) {
      t[start] = m.pool[m.position++]
    }
    return t
  }
  /**
   * 判断浏览器是否支持ArrayBuffer
   */
  var supportArrayBuffer = (function () {
    return !!window.ArrayBuffer;
  })();
  /**
   * 字节流处理实体类
   * @param {String|Array} array 初始化字节流,如果是字符串则按照UTF8的格式写入缓冲区
   * @constructor
   */
  function Stream(array) {
    if (!(this instanceof Stream)) {
      return new Stream(array);
    }
    /**
     * 字节流缓冲区
     * @type {Array}
     */
    this.pool = [];
    if (Object.prototype.toString.call(array) === '[object Array]') {
      this.pool = binaryPot.init(array);
    } else if (Object.prototype.toString.call(array) == "[object ArrayBuffer]") {
      var arr = new Int8Array(array);
      this.pool = binaryPot.init([].slice.call(arr));
    } else if (typeof array === 'string') {
      this.pool = binaryPot.writeUTF(array);
    }
    var self = this;
    //当前流执行的起始位置
    this.position = 0;
    //当前流写入的多少字节
    this.writen = 0;
    //返回当前流执行的起始位置是否已经大于整个流的长度
    this.check = function () {
      return self.position >= self.pool.length
    };
  }
  /**
   * 强制转换为Stream对象
   * @param x
   * @returns {*|Stream}
   */
  Stream.parse = function (x) {
    return binaryPot.convertStream(x);
  };
  Stream.prototype = {
    /**
     * 从缓冲区读取4个字节的长度并转换为int值,position往后移4位
     * @returns {Number} 读取到的数字
     * @description 如果position大于等于缓冲区的长度则返回-1
     */
    readInt: function () {
      if (this.check()) {
        return -1
      }
      var end = "";
      for (var i = 0; i < 4; i++) {
        end += this.pool[this.position++].toString(16)
      }
      return parseInt(end, 16);
    },
    /**
     * 从缓冲区读取1个字节,position往后移1位
     * @returns {Number}
     * @description 如果position大于等于缓冲区的长度则返回-1
     */
    readByte: function () {
      if (this.check()) {
        return -1
      }
      var val = this.pool[this.position++];
      if (val > 255) {
        val &= 255;
      }
      return val;
    },
    /**
     * 从缓冲区读取1个字节,或读取指定长度的字节到传入的数组中,position往后移1或bytesArray.length位
     * @param {Array|undefined} bytesArray
     * @returns {Array|Number}
     */
    read: function (bytesArray) {
      if (this.check()) {
        return -1
      }
      if (bytesArray) {
        return baseRead(this, bytesArray.length | 0, bytesArray)
      } else {
        return this.readByte();
      }
    },
    /**
     * 从缓冲区的position位置按UTF8的格式读取字符串,position往后移指定的长度
     * @returns {String} 读取的字符串
     */
    readUTF: function () {
      var big = (this.readByte() << 8) | this.readByte();
      return binaryPot.readUTF(this.pool.slice(this.position, this.position += big));
    },
    /**
     * 把字节流写入缓冲区,writen往后移指定的位
     * @param {Number|Array} _byte 写入缓冲区的字节(流)
     * @returns {Array} 写入的字节流
     */
    write: function (_byte) {
      var b = _byte;
      if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") {
        [].push.apply(this.pool, b);
        this.writen += b.length;
      } else {
        if (+b == b) {
          if (b > 255) {
            b &= 255;
          }
          this.pool.push(b);
          this.writen++
        }
      }
      return b
    },
    /**
     * 把参数当成char类型写入缓冲区,writen往后移2位
     * @param {Number} v 写入缓冲区的字节
     */
    writeChar: function (v) {
      if (+v != v) {
        throw new Error("writeChar:arguments type is error")
      }
      this.write((v >> 8) & 255);
      this.write(v & 255);
      this.writen += 2
    },
    /**
     * 把字符串按照UTF8的格式写入缓冲区,writen往后移指定的位
     * @param {String} str 字符串
     * @return {Array} 缓冲区
     */
    writeUTF: function (str) {
      var val = binaryPot.writeUTF(str);
      [].push.apply(this.pool, val);
      this.writen += val.length;
    },
    /**
     * 把缓冲区字节流的格式从0至256的区间改为-128至128的区间
     * @returns {Array} 转换后的字节流
     */
    toComplements: function () {
      var _tPool = this.pool;
      for (var i = 0; i < _tPool.length; i++) {
        if (_tPool[i] > 128) {
          _tPool[i] -= 256
        }
      }
      return _tPool
    },
    /**
     * 获取整个缓冲区的字节
     * @param {Boolean} isCom 是否转换字节流区间
     * @returns {Array} 转换后的缓冲区
     */
    getBytesArray: function (isCom) {
      if (isCom) {
        return this.toComplements()
      }
      return this.pool
    },
    /**
     * 把缓冲区的字节流转换为ArrayBuffer
     * @returns {ArrayBuffer}
     * @throw {Error} 不支持ArrayBuffer
     */
    toArrayBuffer: function () {
      if (supportArrayBuffer) {
        return new ArrayBuffer(this.getBytesArray());
      } else {
        throw new Error('not support arraybuffer');
      }
    },
    clear: function () {
      this.pool = [];
      this.writen = this.position = 0;
    }
  };
  return Stream;
});

How to use?

<script src="binary.js"></script>
<script>
   var ts = TinyStream('我叫张亚涛');
   ts.writeUTF('你好');
   console.log('获取缓冲区字节流:',ts.getBytesArray());
   console.log('当前的缓冲区position为:',ts.position,'writen为:',ts.writen);
   console.log('读取第一个utf8字节流:',ts.readUTF());
   console.log('当前的缓冲区position为:',ts.position,'writen为:',ts.writen);
   console.log('读取第二个utf8字节流:',ts.readUTF());
   console.log('当前的缓冲区position为:',ts.position,'writen为:',ts.writen);
</script>

In the future, I don’t have to worry about binary processing in the browser segment! ! ! I hope that sharing this article will be helpful to everyone in learning JavaScript binary related knowledge.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser?How do I optimize JavaScript code for performance in the browser?Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Auto Refresh Div Content Using jQuery and AJAXAuto Refresh Div Content Using jQuery and AJAXMar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

Getting Started With Matter.js: IntroductionGetting Started With Matter.js: IntroductionMar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use