How to split bytes of number into an Uint8Array

Viewed 402

I want to split a js number into the smallest uint8array.

For example :

65 535 = Uint8Array<[255,255]> (0b1111111111111111 = [0b11111111, 0b11111111])
12 356 = Uint8Array<[48,68]> (0b0011000001000100 = [0b00110000, 0b01000100])
1 142 =  Uint8Array<[4,118]> (0b0011000001000100 = [0b00000100, 0b01110110])
400 = Uint8Array<[1,144]> (0b0000000110010000 = [0b00000001, 0b10010000])
256 = Uint8Array<[1,0]> (0b0000000100000000 = [0b00000001, 0b00000000])
64 =  Uint8Array<[64]> (0b0000000001000000 = [0b01000000])
-1 = Uint8Array<[]> I don't want to support negative number

I have try to edited bytes by bytes like that :

const buffer : Uint8Array = new Uint8Array([0,0])
buffer[bytePos] &= ~(1<<bitToEdit); //to set at 0
buffer[bytePos] |= (1 <<bitToEdit) //to set at 1

the bytes edit work but I don't know how to read bytes from the number and how to push bytes of number into this array.

1 Answers

You can do that using BigInt, modulus (%) and Uint8Array.from.

For negative numbers and for 0, this implementation returns an empty Uint8Array (with zero elements). This implementation outputs in Big Endian (as your example shows) by reversing the byte array.

function toByteArray(n) {
  let b = BigInt(n);
  let result = [];
  while (b > 0n) {
    result.push(Number(b % 0x100n));
    b /= 0x100n;
  }
  return Uint8Array.from(result.reverse());
}

console.log(toByteArray(
  0x01_00_00_00_00_00_00_00_03n
)) // Uint8Array(9) [ 1, 0, 0, 0, 0, 0, 0, 0, 3 ]

Related