Kit
Functions

fixBytes

fixBytes(bytes, length): ReadonlyUint8Array | Uint8Array<ArrayBufferLike>

Fixes a Uint8Array to the specified length. If the array is longer than the specified length, it is truncated. If the array is shorter than the specified length, it is padded with zeroes.

Parameters

ParameterTypeDescription
bytesReadonlyUint8Array | Uint8Array<ArrayBufferLike>The byte array to truncate or pad.
lengthnumberThe desired length of the byte array.

Returns

ReadonlyUint8Array | Uint8Array<ArrayBufferLike>

Examples

Truncates the byte array to the desired length.

const bytes = new Uint8Array([0x01, 0x02, 0x03, 0x04]);
const fixedBytes = fixBytes(bytes, 2);
//    ^ [0x01, 0x02]

Adds zeroes to the end of the byte array to reach the desired length.

const bytes = new Uint8Array([0x01, 0x02]);
const fixedBytes = fixBytes(bytes, 4);
//    ^ [0x01, 0x02, 0x00, 0x00]

Returns the original byte array if it is already at the desired length.

const bytes = new Uint8Array([0x01, 0x02]);
const fixedBytes = fixBytes(bytes, 2);
// bytes === fixedBytes

On this page