0

I receive a bytearray and I want to convert it into a intarray.

Is this possible in NodeJS?

Reason to do that:

A proxy receives values from a serialconnection which is a bytearray and I try to decode that and put it into a more specific JSON object.

var uint8Message = new Uint8Array(8),
    output = [];

uint8Message[0] = 40;
uint8Message[1] = 40;
uint8Message[2] = 40;
uint8Message[3] = 40;
uint8Message[4] = 40;
uint8Message[5] = 40;
uint8Message[6] = 40;
uint8Message[7] = 40;

var counter = 0;
var intermediate = [];
for (var i = 0; i< uint8Message.byteLength; i++) {
    if (counter < 4) {
        intermediate.push(uint8Message[i]);
    }

    counter++;
    if (counter === 3 ){
        output.push(new Uint16Array(intermediate));
        counter = 0;
        intermediate = [];
    }
}

console.log(output);

I am sending a intArray which is converted to byteArray from arduino to a NodeJS serialport handler. I want to get 8 integer values in array:

Status and value for four engines.

So in the end I want to have this:

[1,89,2,49,1,28,3,89]

Which is not complete correct with the example. But the example above is for testing.

Amir
  • 1,328
  • 2
  • 13
  • 27
Ipad
  • 393
  • 1
  • 6
  • 22
  • Can you include `javascript` that you have tried at Question? What issue are you having achieving requirement? – guest271314 Jun 08 '17 at 06:46
  • Have you searched? E.g. [*Save byte array to file node JS*](https://stackoverflow.com/questions/41999106/save-byte-array-to-file-node-js) might give you a hint. – RobG Jun 08 '17 at 06:50
  • yes, i did and i came across your topic, but it doesn help. i need the full way to convert bytearray to intarray. this message will never be saved in a file. – Ipad Jun 08 '17 at 06:55
  • I cant find a solution to convert typed array of bytes to have a array of numbers in the end. – Ipad Jun 08 '17 at 06:57
  • What is desired output in this case? Do you want it to be `[673720360, 673720360]`? – Yury Tarabanko Jun 08 '17 at 07:12
  • hi yury, thanks in advance. I clearified the question again maybe, i explain my issues wrongly. in the end i want to have intarray with length 8. Example: [1,89,2,49,1,28,3,89] so yes, for this example, this is what you have provided :-) – Ipad Jun 08 '17 at 07:26

1 Answers1

1

Still not sure I understand your question correctly but if you want to convert Uint8Array to say Uint32Array you could do

const uint8Array = new Uint8Array(8).fill(40)
console.log(new Uint32Array(uint8Array.buffer))

If you need plain old js array you could do

const uint8Array = new Uint8Array(8).fill(40)

const intArray = Array.from(new Uint32Array(uint8Array.buffer))

console.log(Array.isArray(intArray))

Also you might want to take a look at what is called DataView that allows low level access to buffers' contents.

Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98