buffer.seek() / .read() / .write()

buffer.seek(byte)  ·  buffer.read(format, [count])  ·  buffer.write(format, value|array)

Tools to store and read binary data structures.

There is only one string type in mJS which is used to store either textual strings or raw byte buffers.

Payload data returned from RS485 reads, CANBus messages, Http requests, Modbus Queries etc can all be directly parsed into regular numbers easily with these methods.

seek(byte) sets the position (byte 0 = start). (Always call this before .read() or .write()) read(format) returns one value; read(format, count) returns an array of count values. The cursor advances. write(format, value) writes one value; write(format, array) appends the whole array. The cursor advances. The "BIT" format packs elements of 1/0 (or boolean) values into bits — see eip.handle() for a worked status-word example.

  • seek(byte) sets the position (byte 0 = start).
  • read(format) returns one value; read(format, count) returns an array of count values. The cursor advances.
  • write(format, value) writes one value. The cursor advances.
  • write(format, array) appends the whole array. The cursor advances.

The "BIT" format can be used to work with individual bits which could be provided as an array of 1/0(or boolean) or individual values — seeeip.handle()` for a worked status-word example.

Arguments

NameTypeRequiredDefaultDescription
format string yes Format string, e.g. "F32BADC", "U32DCBA".
count / value number | array optional read: how many values to return. write: the value or array to pack.

Example

while(run()){

let data = bin.alloc(8); // allocate a 8 byte buffer

print(bin.toHex(data)); // print the hex for data "0000000000000000"
  
// Write some data to the buffer

data.seek(1); // Set our read/write pointer to start on the second byte
data.write("U8", 255);       // Write a single unsigned 8 with value 255
data.write("U8", [0,1,2,3]);       // Write an array of values as unsigned 8

print(bin.toHex(data)); // print the hex for data "00ff000102030000"
  
  
// Read some data back from the buffer

data.seek(1); // Set the read/write cursor position
print(  data.read("U8") ); // "255"
print( string ( data.read("U8",4) ) ); // "[0,1,2,3]"


waitMS(1000);
  


}