0.0.2 • Published 4 years ago

binary-packer v0.0.2

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

binary-packer

This is a packer/unpacker that provides an (incomplete) interface mimicking Ruby's Array#pack / String#unpack.

Disclaimer

This project SHOULD NOT BE USED IN PRODUCTION SYSTEMS. The API is not complete and it may change at any moment.

Packing data

import { Packer } from 'binay-packer'

new Packer('A3A3A3').pack(['a', 'b', 'c'])
// => Buffer.from("a  b  c  ")

new Packer('a3a3a3').pack(['a', 'b', 'c'])
// => Buffer.from("a\000\000b\000\000c\000\000")

Directives A, a, and Z may be followed by a count, which gives the width of the resulting field. The remaining directives also may take a count, indicating the number of array elements to convert. If the count is an asterisk (*), all remaining array elements will be converted.

DirectiveData TypeMeaning
nInteger16-bit unsigned, network (big-endian) byte order
NInteger32-bit unsigned, network (big-endian) byte order
AStringarbitrary binary string (space padded, count is width)
aStringarbitrary binary string (null padded, count is width)
ZStringsame as a, except that null is added with *
HStringhex string (high nibble first)

Unpacking data

import { Packer } from 'binay-packer'

new Packer('A6Z6').unpack('abc \0\0abc \0\0')
// => ["abc", "abc "]

new Packer('a3a3').unpack('abc \0\0')
// => ["abc", " \000\000"]

new Packer('Z*Z*').unpack('abc \0abc \0')
// => ["abc ", "abc "]

The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (*) will use up all remaining elements.

DirectiveData TypeMeaning
nInteger16-bit unsigned, network (big-endian) byte order
NInteger32-bit unsigned, network (big-endian) byte orderm
AStringarbitrary binary string (remove trailing nulls and ASCII spaces)
aStringarbitrary binary string
ZStringnull-terminated string
HStringhex string (high nibble first)