9

I have a basic question. Say I have a Uint16Array and I have number 4 in it.

data_16=new Uint16Array([4]);  

Now I have a length 1 and byteLength 2;

how do i convert this to Uint8Array.

I do not want to create a new view.

data_8 = new Uint8Array(data_16)

If I do this I get array length 1 and byteLength 1. This is not what I want.

I need to stretch that 16 bit value in 16array into 8 bit values so that 8bit array so it would end up with 2 values int 8 bit array.

I can just create a funtion which converts with shif and to all that stuff. But Can it be done with Array manipulation only?

Evren Bingøl
  • 1,306
  • 1
  • 20
  • 32

2 Answers2

16

You can use the buffer property, i.e. data_8 = new Uint8Array(data_16.buffer, data_16.byteOffset, data_16.byteLength).

qntm
  • 4,147
  • 4
  • 27
  • 41
Steve Campbell
  • 3,385
  • 1
  • 31
  • 43
  • 2
    I suggest `new Uint8Array(data_16.buffer, data_16.byteOffset, data_16.byteLength)`, because in the general case there's no guarantee that `data_16` views all of its backing `ArrayBuffer`. – qntm Jan 13 '20 at 23:12
0

Would like to note that the current accepted answer may not work because of the byte order is platform dependent.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 26 '22 at 21:07
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/33494703) – ahuemmer Dec 27 '22 at 08:10