Recursive AI

Read binary records with JavaScript DataView in C#

OneEcma is a free, open-source JavaScript interpreter for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

DataView reads numbers at byte offsets in a binary record.

Terminal
dotnet add package RecursiveAI.OneEcma

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
var record = engine.Evaluate("""
  const b = new Uint8Array([0, 42, 44, 1]);
  const v = new DataView(b.buffer);
  ({ id: v.getUint16(0, false),
     count: v.getUint16(2, true) });
  """);
foreach (var field in new[] { "id", "count" })
    Console.WriteLine(engine.GetProperty(
        record.AsObject!, field).AsNumber);

Unzip the example, then dotnet run.

The inline bytes 00 2A 2C 01 give C# the record’s ID and count, in that order.

Text
42
300

Full program

The zip includes record.dat, a four-byte sample. The file contains these bytes in hex:

Text
00 2A 2C 01

Bytes 0–1 hold an unsigned big-endian ID; bytes 2–3 hold an unsigned little-endian count. C# reads the file and passes the bytes into JavaScript. The script reads the two fields and returns them as an object. For your own files, see Exchange JavaScript typed arrays with C# for a direct way to pass a C# byte array to JavaScript and read the bytes back.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
byte[] input = File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "record.dat"));
var realm = engine.MainRealm;
var bytes = realm.Construct(realm.Get(realm.Global, "Uint8Array"),
    JsValue.FromNumber(input.Length));
for (int i = 0; i < input.Length; i++)
    realm.Set(bytes.AsObject!, i.ToString(), JsValue.FromNumber(input[i]));
realm.DefineData(realm.Global, "bytes", bytes);
 
var record = engine.Evaluate("""
    const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
    ({ id: view.getUint16(0, false), count: view.getUint16(2, true) });
    """);
var id = (ushort)engine.GetProperty(record.AsObject!, "id").AsNumber;
var count = (ushort)engine.GetProperty(record.AsObject!, "count").AsNumber;
Console.WriteLine($"ID: {id}; count: {count}");

dotnet run prints:

Text
ID: 42; count: 300

A record shorter than four bytes causes the read to throw JsException with a JavaScript RangeError once a field extends past the view.

Variations

Read a field through a smaller view. A view that starts at byte 2 uses offset 0 for the count. The offset passed to getUint16 is relative to the view, not the buffer.

C#
using RecursiveAI.OneEcma;
 
var engine = new ScriptEngine();
Console.WriteLine(engine.Evaluate("""
  const bytes = new Uint8Array([0, 42, 44, 1]);
  const count = new DataView(bytes.buffer, 2, 2);
  count.getUint16(0, true);
  """).AsNumber);
Text
300

The short answer

Use a DataView over the bytes and choose the reader, offset, and byte order for each field. For this record, getUint16(0, false) reads the ID as big-endian, and getUint16(2, true) reads the count as little-endian. Return a JavaScript object and read its properties with engine.GetProperty in C#. These two unsigned 16-bit results fit in C#’s ushort.

How does JavaScript DataView handle endianness?

Endianness is the order of the bytes in a number. Big-endian puts the most significant byte first; little-endian puts it last. In this file, 00 2A means 42 when read big-endian. The last two bytes, 2C 01, mean 300 when read little-endian. Reading that second field as big-endian instead would give 11,265. Both values fit in an unsigned 16-bit field, so a successful read doesn’t tell you whether you used the right order.

DataView defaults to big-endian. Pass false explicitly for a big-endian field and true for a little-endian one so each call shows what the format requires. OneEcma’s binary data notes specify little-endian element access for typed arrays. A Uint16Array therefore isn’t the right tool for one record with both byte orders. The Uint8Array in the full program carries raw bytes; it doesn’t interpret either field.

How do you read part of a buffer with DataView?

Construct the view with the buffer, the start byte, and the number of bytes it should cover. The variation makes a two-byte view at byte 2, so the count starts at view offset 0. This also matters when your source is a typed array that covers only part of a buffer. Using just bytes.buffer would include bytes outside that array; passing bytes.byteOffset and bytes.byteLength keeps the view on the intended window, as the full program does.

getUint16 reads two bytes at the given offset, with no alignment requirement. If only one byte remains, the read throws rather than padding it. For an input file intended to contain exactly one of these records, check that its length is four before decoding. A bounds error catches a truncated field but won’t tell you about extra data or an incorrect format.

All oneecma recipes