Skip to content

Instantly share code, notes, and snippets.

@yurynix
Last active August 29, 2015 14:10
Show Gist options
  • Save yurynix/9ea0662344401584f594 to your computer and use it in GitHub Desktop.
Save yurynix/9ea0662344401584f594 to your computer and use it in GitHub Desktop.
function Data(a, b, c) {
this.a = a;
this.b = b;
this.c = c;
}
/* Statics */
Data.getBufferDesc = function Data_getBufferDesc() {
// avoid new instance here, but i'm lazy.
return [
{ type: 'UInt32BE', size: 32 },
{ type: 'UInt32BE', size: 32 },
{ type: 'FloatBE', size: 32 } // 32 bit float
];
};
function char2Data(buff) {
var results = [],
result,
values = [],
bufferDesc = Data.getBufferDesc(),
fullDataSize = bufferDesc.reduce(function(prev, next) { prev + (next.size / 8); }),
value,
currentDesc,
j = 0,
i = 0;
if ((buff.length % fullDataSize) === 0 ) {
throw new Error("Your buffer has invalid size, should be deviceable by " + fullDataSize);
}
while (i < buff.length -1) {
currentDesc = bufferDesc[j];
value = buff['read' + currentDesc.type](i);
values.push( value );
i += currentDesc.size / 8;
j = ( j + 1 ) % bufferDesc.length;
if (j === 0) {
result = Object.create(Data.prototype); // create instance
Data.apply(result, values); // call c-tor
results.push( result );
values = [];
}
}
return results;
}
var buf = new Buffer([ 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC,
0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC
]);
console.log( char2Data( buf ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment