0.0.6 • Published 7 years ago

object-byte-converter v0.0.6

Weekly downloads
4
License
ISC
Repository
github
Last release
7 years ago

object-byte-converter

Convert between Javascript object and byte array

Float and Double are not supported yet

How to use

npm install object-byte-converter --save

Example

To serialize/deserialize C struct below

struct struct2 {
  int field6;
  long int field7;
};
struct struct1 {
  int field1;
  unsigned char field2;
  char field3[30];
  long int field4[10];
  struct2 field5;
};

Create a typedef...

const example_typedefs = {
  _settings_: {
    // CPU endianess (Little endian if not specified)
    isBigEndian: true 
  },
  // Typedef for struct1
  struct1: {
    // int field1;
    field1: { 
      type: "int", // Signed integer e.g. char, short, int, long
      size: 2 // Number of byte
    },
    // unsigned char field2;
    field2: { 
      type: "uint", // Unsigned integer e.g. unsigned char, ...
      size: 1 
    },
    // char field3[30]
    field3: { 
      type: "string", // String e.g. char[30]
      size: 30 // Size of char array
    },
    // long int field4[10];
    field4: { 
      type: "int", 
      size: 4, 
      isArray: true,
      length: 10
    },
    // struct2 field5; 
    field5: {
      type: "struct2",
      size: 0 // size is not used for struct
    }
  },
  // Typedef for struct2
  struct2: {
    // float field6;
    field6: { type: "int", size: 2 },
    // double field7
    field7: { type: "int", size: 4 },
  }
};

Serialization

const data = {
  field1: -10,
  field2: 20,
  field3: "Test",
  field4: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  field5: {
    field6: -1,
    field7: -1
  }
};
const objectByteConverter = require('object-byte-converter');
let bytes = objectByteConverter.toByteArray(data, "struct1", example_typedefs);

Deserialization

let obj = objectByteConverter.toObject(bytes, "struct1", example_typedefs);