JavaScript front end development to implement binary read write operations
- 2020-09-28 08:44:20
- OfStack
For the relevant introduction of javascript front-end development to implement base 2 read-write operation, please see the following details. This article is very detailed and has reference value.
For a variety of reasons, it is not possible to operate in base 2 as nodejs does in the browser.
I recently wrote a helper class for reading and writing base 2 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 = {
/**
* Initializes the byte stream , the -128 to 128 Change the interval of 0-256 The range of . 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(' Illegal byte stream ')
}
}
return array;
},
/**
* the 1 Segment string according to utf8 The code is written to the buffer
* @param {String} str The string to be written to the buffer
* @param {Boolean} isGetBytes Whether to get only content bytes ( Does not include 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 >= 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);
}
},
/**
* the 1 String throttling follows utf8 Code read out
* @param arr Byte stream
* @returns {String} Read the 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
},
/**
* Converted to Stream object
* @param x
* @returns {Stream}
*/
convertStream: function (x) {
if (x instanceof Stream) {
return x
} else {
return new Stream(x)
}
},
/**
* the 1 Segment string converted to mqtt format
* @param str
* @returns {*|Array}
*/
toMQttString: function (str) {
return this.writeUTF(str)
}
};
/**
* Reads a byte stream of the specified length into the specified array
* @param {Stream} m Stream The instance
* @param {number} i Read length
* @param {Array} a Stored array
* @returns {Array} Stored array
*/
function baseRead(m, i, a) {
var t = a ? a : [];
for (var start = 0; start < i; start++) {
t[start] = m.pool[m.position++]
}
return t
}
/**
* Determine if the browser supports it ArrayBuffer
*/
var supportArrayBuffer = (function () {
return !!window.ArrayBuffer;
})();
/**
* Byte stream handles entity classes
* @param {String|Array} array Initializes the byte stream , If it is a string, follow UTF8 The format of write 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 at which the current flow executes
this.position = 0;
// How many bytes are being written by the current stream
this.writen = 0;
// Returns whether the start of the current stream execution is already greater than the length of the entire stream
this.check = function () {
return self.position >= self.pool.length
};
}
/**
* Cast to Stream object
* @param x
* @returns {*|Stream}
*/
Stream.parse = function (x) {
return binaryPot.convertStream(x);
};
Stream.prototype = {
/**
* Read from the buffer 4 The length of 2 bytes and converted to int value ,position Move back 4 position
* @returns {Number} The number that was read
* @description if position Returns the buffer length greater than or equal to -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);
},
/**
* Read from the buffer 1 bytes ,position Move back 1 position
* @returns {Number}
* @description if position Returns the buffer length greater than or equal to -1
*/
readByte: function () {
if (this.check()) {
return -1
}
var val = this.pool[this.position++];
if (val > 255) {
val &= 255;
}
return val;
},
/**
* Read from the buffer 1 bytes , Or read a specified length of bytes into the incoming array ,position Move back 1 or bytesArray.length position
* @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();
}
},
/**
* Buffer from position Position according to the UTF8 Format to read a string ,position Move back the specified length
* @returns {String} Read 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 ,writen Move back the specified bit
* @param {Number|Array} _byte The bytes that write to the buffer ( flow )
* @returns {Array} Write byte stream
*/
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
},
/**
* Think of parameters as char Type write buffer ,writen Move back 2 position
* @param {Number} v The bytes that write 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
},
/**
* String according to UTF8 The format of write buffer ,writen Move back the specified bit
* @param {String} str string
* @return {Array} The buffer
*/
writeUTF: function (str) {
var val = binaryPot.writeUTF(str);
[].push.apply(this.pool, val);
this.writen += val.length;
},
/**
* The format of the buffer byte stream from 0 to 256 Change the interval of -128 to 128 The range of
* @returns {Array} 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
},
/**
* Gets the bytes of the entire buffer
* @param {Boolean} isCom Whether to convert byte stream intervals
* @returns {Array} The converted buffer
*/
getBytesArray: function (isCom) {
if (isCom) {
return this.toComplements()
}
return this.pool
},
/**
* Converts 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?
<script src="binary.js"></script>
<script>
var ts = TinyStream(' My name is Zhang Yatao ');
ts.writeUTF(' hello ');
console.log(' Gets a buffer byte stream :',ts.getBytesArray());
console.log(' Current buffer position for :',ts.position,'writen for :',ts.writen);
console.log(' Read the first 1 a utf8 Byte stream :',ts.readUTF());
console.log(' Current buffer position for :',ts.position,'writen for :',ts.writen);
console.log(' Read the first 2 a utf8 Byte stream :',ts.readUTF());
console.log(' Current buffer position for :',ts.position,'writen for :',ts.writen);
</script>
In the future, I won't have to worry about handling base 2 in the browser segment!! I hope this article will be helpful for you to learn the javascript2 base system.