@react-frontend-developer/buffers

node v8.17.0
version: master
endpointsharetweet
const { Buffers, TypedArrays } = require("@react-frontend-developer/buffers")
const buffer = Buffer.from('Some string...', 'utf16le') const arrayBuffer = Buffers.copyToArrayBuffer(buffer)
const uint16Array = new Uint16Array(arrayBuffer)
const uint32Array = new Uint32Array(arrayBuffer)
const uint8Array = new Uint8Array(arrayBuffer)
uint16Array[0].toString(16).padStart(4, '0')
uint32Array[0].toString(16).padStart(8, '0')
uint8Array[0].toString(16).padStart(2, '0')
And now some example with using TypedArrays helper
const testString = 'aBCD' TypedArrays.string2Uint8Array(testString, 'utf8')
default is 'utf16le':
TypedArrays.string2Uint8Array(testString)
TypedArrays.string2Uint8Array(testString, 'hex')
const testBinaryString = 'a\u0000b\u0023c\u00ab' TypedArrays.string2Uint8Array(testBinaryString, 'binary')
And of course you can create directly to ArrayBuffer so that you can get any other TypedArray view on it:
new Uint16Array(TypedArrays.string2ab(testString, 'hex'))
Converting to string is easy. Let's get some example inputs first:
const testUint8ArrayUtf8 = Buffers.copyToUint8Array(Buffers.fromString(testString, 'utf8')) const testUint8ArrayUtf16 = Buffers.copyToUint8Array(Buffers.fromString(testString)) const testUint8ArrayHex = Buffers.copyToUint8Array(Buffers.fromString(testString, 'hex')) const testUint8ArrayBinary = Buffers.copyToUint8Array(Buffers.fromString(testBinaryString, 'binary'))
TypedArrays.uint8Array2string(testUint8ArrayUtf8, 'utf8')
TypedArrays.uint8Array2string(testUint8ArrayUtf16)
TypedArrays.uint8Array2string(testUint8ArrayHex, 'hex')
TypedArrays.uint8Array2string(testUint8ArrayBinary, 'binary')
And of course, you can have plain ArrayBuffer as the input as well for more flexibility:
TypedArrays.ab2string(testUint8ArrayUtf16.buffer)
Loading…

no comments

    sign in to comment