JavaScript frontend development-Implementation of binary read/write operations-javascript skills

Source: Internet
Author: User
This article describes how to implement binary read/write operations in JavaScript front-end development. For more information, see Introduction to the implementation of binary read/write operations in javascript front-end development, please refer to the following details. This article is very detailed and has reference value.

For various reasons, the browser cannot operate binary like nodejs.

Recently I wrote a help class for reading and writing binary data in a browser.

! 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 = {/*** initialize the byte stream and change the range from-128 to 128 to the range from 0. easy to calculate * @ param {Array} array byte stream Array * @ return {array} converted byte stream 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 ('invalid byte stream')} return array ;}, /*** write a String to the buffer according to UTF-8 encoding * @ param {String} str: String to be written into the buffer * @ param {Boolean} isGetBytes: whether to get only content bytes (not including the first two placeholder bytes) * @ returns {Array} byte stream */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> = 1 28 & 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 );}}, /*** read a String of byte streams according to utf8 encoding * @ param arr byte stream * @ returns {String} Read 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 +? (? = 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},/*** convert to Stream object * @ param x * @ returns {Stream} */convertStre Am: function (x) {if (x instanceof Stream) {return x} else {return new Stream (x )}}, /*** convert a string to mqtt format * @ param str * @ returns {* | Array} */toMQttString: function (str) {return this. writeUTF (str )}}; /*** read byte streams of the specified length to the specified Array * @ param {Stream} m Stream instance * @ param {number} I read length * @ param {Array} a saved * @ returns {Array} Array */function baseRead (m, i, a) {var t =? A: []; for (var start = 0; start <I; start ++) {t [start] = m. pool [m. position ++]} return t}/*** determines whether the browser supports ArrayBuffer */var supportArrayBuffer = (function () {return !! Window. arrayBuffer;}) ();/*** byte stream processing entity class * @ param {String | Array} array initializes the byte stream, if it is a string, write the buffer * @ constructor */function Stream (array) {if (! (This instanceof Stream) {return new Stream (array);}/*** byte Stream buffer * @ 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; // the starting position of the current stream execution this. position = 0; // The number of bytes written to the current stream. this. writen = 0; // return whether the starting position of the current stream execution is greater than the length of the whole stream. check = function () {return self. position> = self. pool. length};}/*** forcibly converted to Stream object * @ param x * @ returns {* | Stream} */Stream. parse = function (x) {return binaryPot. convertStream (x) ;}; Stream. prototype = {/*** read the length of 4 bytes from the buffer and convert it to int value, posit Ion moves back 4 digits * @ returns {Number} to read the Number * @ description. If the position is greater than or equal to the length of the buffer,-1 */readInt: function () is returned () {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) ;},/*** read 1 byte from the buffer, position move back 1 bit * @ returns {Number} * @ description if position is greater than or equal to the length of the buffer,-1 */readByte: function () {if (this. check () {retu Rn-1} var val = this. pool [this. position ++]; if (val> 255) {val & = 255;} return val ;},/*** reads 1 byte from the buffer, or read the specified length of byte to the input array, move position back 1 or bytesArray. length bit * @ 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 ();}}, /*** Read the String from the position of the buffer in UTF8 format, and move the position back to the String read by the specified length * @ returns {String} */readUTF: function () {var big = (this. readByte () <8) | this. readByte (); return binaryPot. readUTF (this. pool. slice (this. position, this. position + = big) ;},/*** writes the byte stream to the buffer zone, the specified bit * @ param {Number | Array} _ byte of the buffer written by writen * @ returns {Array} */write: function (_ byte) {var B = _ byte; if (Object. protot Ype. 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},/*** treats the parameter as a char-type write buffer, writen moves 2 bits back * @ param {Number} v The Byte written to the buffer */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},/*** write the string to the buffer in UTF8 format, the specified position * @ param {String} str String * @ return {Array} buffer */writeUTF: function (str) {var val = binaryPot. writeUTF (str); []. push. apply (this. pool, val); this. writen + = val. length ;}, /*** change the format of the buffer byte stream from 0 to 256 to the range from-128 to 128 * @ returns {Array} to the converted byte stream */toComplements: function () {var _ tPool = this. pool; for (var I = 0; I <_ tPool. length; I ++) {if (_ tPool [I]> 128) {_ tPool [I]-= 256} return _ tPool }, /*** get the bytes of the entire buffer * @ param {Boolean} whether isCom converts the byte stream range * @ returns {Array} the converted buffer */getBytesArray: function (isCom) {if (isCom) {return this. toComplements ()} return this. pool},/*** switch the byte stream of the buffer to ArrayBuffer * @ returns {ArrayBuffer} * @ throw {Error} does not support 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 it?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.