Encode and decode unsigned integers to and from byte buffers.
npm install uint-buffer
npm install uint-buffer
`
Use
$3
Use the uint-buffer.js file in the dist folder:
`html
`
Or load it from the jsDelivr CDN:
`html
`
Or load it from unpkg:
`html
`
$3
`javascript
const UintBuffer = require('uint-buffer').UintBuffer;
// A byte buffer, array and Uint8Array can be used
let buffer = [];
// Create a UintBuffer to handle 32-bit numbers
let uintBufer = new UintBuffer(32);
// Pack a value
uintBufer.pack(buffer, 2045);
// Check the buffer
console.log(buffer);
`
API
`javascript
/**
* A class to write and read unsigned ints to and from byte buffers.
*/
export class UintBuffer {
/**
* @param {number} bits The number of bits used by the integer.
*/
constructor(bits) {
/**
* The number of bits used by one number.
* @type {number}
*/
this.bits;
/**
* The number of bytes used by one number.
* @type {number}
*/
this.bytes;
}
/**
* Write one unsigned integer to a byte buffer.
* @param {!Uint8Array|!Array} buffer An array of bytes.
* @param {number} num The number.
* @param {number=} index The index being written in the byte buffer.
* @return {number} The next index to write on the byte buffer.
* @throws {TypeError} If num is not a number.
* @throws {RangeError} On overflow.
*/
pack(buffer, num, index=0) {}
/**
* Unpack one unsigned integer from a byte buffer.
* @param {!Uint8Array|!Array} buffer An array of bytes.
* @param {number=} index The index to read.
* @return {number} The number.
* @throws {RangeError} On overflow.
*/
unpack(buffer, index=0) {}
/**
* Write one unsigned integer to a byte buffer.
* This method assumes the input has already been validated
* and should be used only if you know what you are doing.
* @param {!Uint8Array|!Array} buffer An array of bytes.
* @param {number} num The number.
* @param {number=} index The index being written in the byte buffer.
* @return {number} The next index to write on the byte buffer.
*/
packUnsafe(buffer, num, index=0) {}
/**
* Read one unsigned integer from a byte buffer.
* Does not check for overflows.
* @param {!Uint8Array|!Array} buffer An array of bytes.
* @param {number=} index The index to read.
* @return {number}
*/
unpackUnsafe(buffer, index=0) {
/* @type {number} /
let num = 0;
for(let x = 0; x < this.bytes; x++) {
num += buffer[index + x] * Math.pow(256, x);
}
return num;
}
}
``