How do I get the size of the DataView type (e.g. Uint32 = 4, Float64 = 8) to advance the offset?
I am parsing a serialized object with a DataView and want to be able to increment the offset variable depending on the size of the data. I would rather not override variables for simple things likeBYTES_PER_UINT16
...
var dv = new DataView(payload);
var offset = 0;
anObject.field1 = dv.getUint8(offset);
offset += BYTES_PER_UINT8;
anObject.field2 = dv.getUint32(offset, true);
offset += BYTES_PER_UINT32;
...
+3
source to share
1 answer
You need to wrap them in an object that does it for you.
For example:
function DataViewExt(o) {
this.view = new DataView(o);
this.pos = 0;
}
DataViewExt.prototype = {
getUint8: function() {
return this.view.getUint8(this.pos++);
},
getUint16: function() {
var v = this.view.getUint16(this.pos);
this.pos += 2;
return v
},
// etc...
};
Now you can create an instance:
var dv = new DataViewExt(payload);
var uint8 = dv.getUint8(); // advances 1 byte
var uint16 = dv.getUint16(); // advances 2 bytes
...
console.log("Current position:", dv.pos);
Change your script.
0
source to share