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.

6
  • Can you include javascript that you have tried at Question? What issue are you having achieving requirement? Commented Jun 8, 2017 at 6:46
  • Have you searched? E.g. Save byte array to file node JS might give you a hint. Commented Jun 8, 2017 at 6: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. Commented Jun 8, 2017 at 6:55
  • I cant find a solution to convert typed array of bytes to have a array of numbers in the end. Commented Jun 8, 2017 at 6:57
  • What is desired output in this case? Do you want it to be [673720360, 673720360]? Commented Jun 8, 2017 at 7:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

the first attempt looks pretty good! i will test this, thanks
thank you yury! this was exactly what i was looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.