binstruct 0.2.2 copy "binstruct: ^0.2.2" to clipboard
binstruct: ^0.2.2 copied to clipboard

A binary struct parser/builder similar to Python's construct

example/main.dart

import 'package:binstruct/binstruct.dart';

void main() {
  // Define a binary struct with three fields:
  // - a 1-byte unsigned int ('a')
  // - a 2-byte signed int ('b')
  // - a binary struct with two fields ('c'):
  //   - a 1-byte BitStruct ('d'):
  //     - a 1-bit unsigned int ('e')
  //     - a 7-bit unsigned int ('f')
  //   - a 1-byte unsigned int ('g')
  final struct = BinStruct([
    Uint8('a'),
    Int16('b'),
    StructField(
        'c',
        BinStruct([
          BitStruct('d', [BitField('e', 1), BitField('f', 7)]),
          Uint8('g')
        ])),
  ]);

  // Build binary data from a map
  final bytes = struct.build({
    'a': 42,
    'b': -1234,
    'c': {
      'd': {
        'e': 1,
        'f': 46
      }, 
      'g': 255
    }
  });

  print('Binary bytes: $bytes'); // Prints [42, 251, 46, 174, 255]

  // Parse the bytes back to a Dart map
  final parsed = struct.parse(bytes);

  // Prints {a: 42, b: -1234, c: {d: {e: 0, f: 42}, g: 255}}
  print('Parsed data: $parsed');

  // Validate the parsed values
  print(parsed['a'] == 42); // Prints true
  print(parsed['b'] == -1234); // Prints true
  print(parsed['c']['d']['e'] == 1); // Prints true
  print(parsed['c']['d']['f'] == 46); // Prints true
  print(parsed['c']['g'] == 255); // Prints true
}
0
likes
0
points
37
downloads

Publisher

unverified uploader

Weekly Downloads

A binary struct parser/builder similar to Python's construct

License

unknown (license)

More

Packages that depend on binstruct