Search code examples
javascriptdata-conversion

how to convert raw data to int32 in javascript


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?


Solution

  • 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);