Skip to content

Repository files navigation

 _ _ _ ___| |_ _ __ _ _ ___| |_ (_)___ / __| __| '__| | | |/ __| __| | / __|
\__ \ |_| | | |_| | (__| |_ _ | \__ \
|___/\__|_| \__,_|\___|\__(_)/ |___/
|__/ 

Python struct module port to JavaScript — pack and unpack binary data using format strings.

Works in Node.js and browsers (no dependencies, uses Web APIs: ArrayBuffer, DataView, BigInt).

Install

npm install @teskevirtualsystem/struct.js

Usage

import{pack,unpack,calcSize}from"@teskevirtualsystem/struct.js";// Pack an unsigned int (1234) — returns ArrayBufferconstbuf=pack("I",1234);// Unpack it backunpack("I",buf);// [1234]// Pack multiple fieldsconstbuf2=pack("Ifc",9184,10.5,"a");unpack("Ifc",buf2);// [9184, 10.5, "a"]// Big-endianconstbuf3=pack(">I",1234);unpack(">I",buf3);// [1234]// Repeat countsconstbuf4=pack("3I",10,20,30);unpack("3I",buf4);// [10, 20, 30]// Fixed-width stringsconstbuf5=pack("10s","hello");unpack("10s",buf5);// ["hello\0\0\0\0\0"]// Pascal strings (length-prefixed)constbuf6=pack("10p","hello");unpack("10p",buf6);// ["hello"]// Calculate size without packingcalcSize("IHHf");// 14

API

unpack(fmt, input)Array

Unpacks binary data according to the format string.

Input types:string (legacy), ArrayBuffer, or DataView.

pack(fmt, ...values)ArrayBuffer

Packs values into an ArrayBuffer according to the format string.

calcSize(fmt)number

Returns the byte size of the packed data for a given format.

StructError

Error class thrown on invalid formats, buffer size mismatches, value count mismatches, or out-of-range values.

Format String

First character (optional) sets endianness:

PrefixEndianness
@, =, <Little-endian
>, !Big-endian

Remaining characters define fields. A numeric prefix repeats the field:

FormatC TypeSizeDescription
xpad byte1Skips bytes (no value consumed)
cchar1Single character string
bsigned char1Integer
Bunsigned char1Integer
?_Bool1Boolean
hshort2Integer
Hunsigned short2Integer
iint4Integer
Iunsigned int4Integer
llong4Integer
Lunsigned long4Integer
qlong long8BigInt
Qunsigned long long8BigInt
ffloat4Float
ddouble8Double
schar[]NFixed-width string (N bytes, padded with \0)
pchar[]NPascal string (1 length byte + N-1 data bytes)
Pvoid *4Integer (pointer, 32-bit)

Dev

npm run build # Copy src/ to dist/
npm test# Run tests (vitest)
npm run test:watch # Watch mode
npm run lint # ESLint
npm run typecheck # TypeScript declaration check

License

MIT

About

The implementation of Python Struct to Javascript

Topics

Resources

Stars

7 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages