Converting Numeric Values to Binary in JavaScript Using ArrayBuffer and DataView
ArrayBuffer and DataView Fundamentals
JavaScript exposes raw binary storage through the ArrayBuffer object, a fixed-length byte buffer whose cnotents cannot be accessed dircetly. To read or write data, wrap the buffer in a view such as DataView, which offers low-level, endian-aware methods for all common numeric types.
const buf = new ArrayBuffer(8); // 8-byte buffer
const view = new DataView(buf); // endian-agnostic accessor
Endianness
Multi-byte values can be stored in little-endian (least-significant byte first) or big-endian (most-significant byte first) order. DataView lets you choose explicitly:
view.setInt32(0, 0x12345678, true); // little-endian
view.setInt32(0, 0x12345678, false); // big-endian (default)
Encoding 16- and 32-bit Integers
Store a 16-bit signed integer followed by a 32-bit signed integer in a 6-byte buffer:
const bytes = new ArrayBuffer(6);
const dv = new DataView(bytes);
dv.setInt16(0, 3000); // offset 0, value 3000
dv.setInt32(2, 987654); // offset 2, value 987654
Handling 64-bit Values
JavaScript numbers are IEEE-754 doubles and cannot safely represent the full 64-bit range. Use a high/low split or a third-party library such as long:
import Long from 'long';
const val = Long.fromString('123456789012345');
const buf = new ArrayBuffer(8);
const dv = new DataView(buf);
dv.setInt32(0, val.high); // high 32 bits
dv.setInt32(4, val.low); // low 32 bits
Decoding Binary Back to Numbers
Retrieve the previous stored values:
const shortVal = dv.getInt16(0);
const intVal = dv.getInt32(2);
const longVal = Long.fromBits(dv.getInt32(4), dv.getInt32(0));
Complete round-trip example:
import Long from 'long';
const payload = new ArrayBuffer(14);
const v = new DataView(payload);
// write
v.setInt16(0, 42);
v.setInt32(2, 202404);
const l = Long.fromString('9223372036854775807');
v.setInt32(6, l.high);
v.setInt32(10, l.low);
// read
const a = v.getInt16(0);
const b = v.getInt32(2);
const c = Long.fromBits(v.getInt32(10), v.getInt32(6));