Reputation: 574
I get this data = [0, 4, -109, -31]
from modbus and I know this data = 300001
but I don't know how to convert it properly to get to that 300001
.
I've tried lots of methods found online but I haven't got it to work.
Thank you for any help
Edit:
As I understand 0
needs to be shifted by 24
, 4
shifted by 16
, -109 (256-109 = 147)
so it would be 147
and needs to be shifted by 8
and the last one -31 (256-31 = 225)
we take as is.
So quick recap data = [0, 4, 147, 225]
and 0 * 2^24 + 4 * 2^16 + 147 * 2^8 + 225 = 300001
Now this needs to be codified.
Are there any proper ways to do it in js?
Upvotes: 2
Views: 542
Reputation: 4180
you can bitshift and sum your numbers:
data = [0, 4, -109, -31]
console.log( data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3] );
Upvotes: 3
Reputation: 386654
You need a data view with a buffer and set the bytes
var data = [0, 4, -109, -31]
// Create a data view of a buffer
var view = new DataView(new ArrayBuffer(4));
// set bytes
data.forEach((v, i) => view.setInt8(i, v));
var num = view.getInt32(0);
console.log(num);
Upvotes: 5