UNPKG

@pefish/js-node-assist

Version:
94 lines 2.49 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const bignumber_js_1 = __importDefault(require("bignumber.js")); class BufferUtil { /** * 以hex编码转换为十进制的bytes数组 * @returns {string} */ static toDecimalNumberArray(src) { const temp = this.correctEmptyBuffer(src); return [].slice.call(temp); } /** * 以hex编码转化为二进制字符串 * @returns {string} */ static toBinString(src) { const temp = src; return this.toDecimalNumberArray(temp).map(function (x) { let str = x.toString(2); while (str.length < 8) { str = '0' + str; } return str; }).join(''); } /** * 字节集直接转化为十六进制字符串。 * @returns {string} */ static toHexString(src, prefix = true) { const temp = src.toString('hex'); if (prefix === false) { return temp; } else { return '0x' + temp; } } /** * 以hex编码转化为十进制字符串 * @returns {string} */ static toDecimalString(src) { if (this.getBytesLength(src) === 0) { return '0'; } return new bignumber_js_1.default(src.toString('hex'), 16).toString(10); } /** * 纠正空buffer * @returns {correctEmptyBuffer} */ static correctEmptyBuffer(src) { let temp = src; if (this.getBytesLength(src) === 0) { temp = new Buffer('00', 'hex'); } return temp; } /** * 获取字节数 */ static getBytesLength(src) { return src.length; } /** * 反转Buffer, 不改变自身 * @returns {Buffer} */ static reverseBuffer(src) { return this.correctEmptyBuffer(this.deepCopy(src)).reverse(); } /** * 深拷贝 * @returns {*} */ static deepCopy(src) { const tempBuffer = Buffer.alloc(src.length); src.copy(tempBuffer, 0, 0, src.length); return tempBuffer; } static toUint8Array(src) { return new Uint8Array(src); } static toUtf8String(src) { return src.toString(); } } exports.default = BufferUtil; //# sourceMappingURL=buffer.js.map