Javascriptでバイナリの構造体を扱う

ArrayBufferとDataViewとUint8Arrayでごにょごにょすればいいらしい。

function setData()
{
  const longitude = 139.6917;
  const year  = 2023;
  const month = 5;
  const day   = 28;
  const hour  = 12;
  const min   = 30;

  const aBuffer = new ArrayBuffer(10);
  const dView = new DataView(aBuffer);
  const LITTLE_ENDIAN = true;
  dView.setFloat32(0, longitude, LITTLE_ENDIAN);
  dView.setUint16( 4, year,      LITTLE_ENDIAN);
  dView.setUint8(  6, month,     LITTLE_ENDIAN);
  dView.setUint8(  7, day,       LITTLE_ENDIAN);
  dView.setUint8(  8, hour,      LITTLE_ENDIAN);
  dView.setUint8(  9, min,       LITTLE_ENDIAN);
  const bArray = new Uint8Array(aBuffer);

  console.log(bArray);
  return bArray;
}

function getData(bArray)
{
  const aBuffer = bArray.buffer;
  const dView = new DataView(aBuffer);
  const LITTLE_ENDIAN = true;

  const longitude = dView.getFloat32(0, LITTLE_ENDIAN);
  const year      = dView.getUint16( 4, LITTLE_ENDIAN);
  const month     = dView.getUint8(  6, LITTLE_ENDIAN);
  const day       = dView.getUint8(  7, LITTLE_ENDIAN);
  const hour      = dView.getUint8(  8, LITTLE_ENDIAN);
  const min       = dView.getUint8(  9, LITTLE_ENDIAN);

  const longitudeF4 = Math.round(longitude * 10000) / 10000;

  console.log(longitudeF4);
  console.log(year);
  console.log(month);
  console.log(day);
  console.log(hour);
  console.log(min);
}

const bArray = setData();
getData(bArray);

実行結果

Uint8Array(10) [
  19, 177, 11, 67, 231,
   7,   5, 28, 12,  30
]
139.6917
2023
5
28
12
30