How to convert hex text file to jpeg - jpeg

I have been given a text file containing hex data which I know forms a jpeg image. Below is an example of the format:
FF D8 FF E0 00 10 4A 46 49 46 00 01 02 00 00 64 00 64 00 00 FF E1 00 B8 45 78 69 00 00 4D
This is only a snippet but you get the idea.
Does anyone know how I could convert this back into the original jpeg?

To convert from a hex string to a byte you use the Convert.ToByte with a base 16 parameter.
To convert a byte array to a Bitmap you put it in a Stream and use the Bitmap(Stream) constructor:
using System.IO;
//..
string hexstring = File.ReadAllText(yourInputFile);
byte[] bytes = new byte[hexstring.Length / 2];
for (int i = 0; i < hexstring.Length; i += 2)
bytes[i / 2] = Convert.ToByte( hexstring.Substring(i, 2), 16);
using (MemoryStream ms = new MemoryStream(bytes))
{
Bitmap bmp = new Bitmap(ms);
// now you can do this:
bmp.Save(yourOutputfile, System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose(); // dispose of the Bitmap when you are done with it!
// or that:
pictureBox1.Image = bmp; // Don't dispose as long as the PictureBox needs it!
}
I guess that there are more LINQish way but as long as it works..

Related

Handling ArrayBuffer in mqtt message callback

A mqtt client send a binary message to certain topic. My node.js client subscribes to the topic and recieves the binary data. As our architecture payload is Int16Array. But I cannot cast it successfully to Javascript array.
//uint16 array [255, 256, 257, 258] sent as message payload, which contents <ff 00 00 01 01 01 02 01>
When I do this:
mqttClient.on("message", (topic, payload) => {
console.log(payload.buffer);
})
The output like:
ArrayBuffer {
[Uint8Contents]: <30 11 00 07 74 65 73 74 6f 7a 69 ff 00 00 01 01 01 02 01>,
byteLength: 19
}
which cant be cast to Int16Array because of odd length
It also contains more bytes than the original message
As it seems the original bytes exist at the end of the payload, which is offset for some reason.
Buffer also contains the offset and byte length information inside. By using them casting should be successful.
let arrayBuffer = payload.buffer.slice(payload.byteOffset,payload.byteOffset + payload.byteLength)
let int16Array = new Int16Array(arrayBuffer)
let array = Array.from(arrayBuffer)

BSON/Binary to string for MongoDB Object ID in Node JS

I am working on Change Streams introduced in MongoDB Version 3.6. Change Streams have a feature where I can specify to start streaming changes from a particular change in history. In native driver for Node.js, to resume change stream, it says (documentation here)
Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.
When I print it in console, this is what I am getting
{ _id:
{ _data:
Binary {
_bsontype: 'Binary',
sub_type: 0,
position: 49,
buffer: <Buffer 82 5a 61 a5 4f 00 00 00 01 46 64 5f 69 64 00 64 5a 61 a5 4f 08 c2 95 31 d0 48 a8 2e 00 5a 10 04 7c c9 60 de de 18 48 94 87 3f 37 63 08 da bb 78 04> } },
...
}
My problem is I do not know how to store the _id of this format in a database or a file. Is it possible to convert this binary object to string so I can use it later to resume my change stream from that particular _id. Example code would be greatly appreciated.
Convert BSON Binary to buffer and back
const Binary = require('mongodb').Binary;
const fs = require('fs');
Save _data from _id:
var wstream = fs.createWriteStream('/tmp/test');
wstream.write(lastChange._id._data.read(0));
wstream.close();
Then rebuild resumeToken:
fs.readFile('/tmp/test', void 0, function(err, data) {
const resumeToken = { _data: new Binary(data) };
});

Decoding UDP Data with Node_pcap

I am trying to build quick nodejs script to look at some data in my network. Using node_pcap I manage to decode almost everything but the payload data that is end through the UDP protocol. This is my code (fairly basic but gives me the headers and payloads)
const interface = 'en0';
let filter = 'udp';
const pcap = require('pcap'),
pcap_session = pcap.createSession(interface, filter),
pcap_session.on('packet', function (raw_packet) {
let packet = pcap.decode.packet(raw_packet);
let data = packet.payload.payload.payload.data;
console.log(data.toString()); // not full data
});
When I try to print data using toString() method, it gives me most of the data but the beginning. I have something like this printed :
Li?��ddn-�*ys�{"Id":13350715,... I've cut the rest of the data which is the rest of the JSON.
But I am suspecting that the bit of data that I can't read contain some useful info such has how many packet, offset packet and so on..
I manage to get a part of it from the buffer from a payload :
00 00 00 01 52 8f 0b 4a 4d 3f cb de 08 00 01 00 00 00 04 a4 00 00 26 02 00 00 26 02 00 00 00 03 00 00 00 00 00 00 09 2d 00 00 00 00 f3 03 01 00 00 2a 00 02 00 79 00 05 73 01 d2
Although I have an idea of what kind of data it can be I have no idea of its structure.
Is there a way that I could decode this bit of the buffer ? I tried to look at some of the buffer method such as readInt32LE, readInt16LE but in vain. Is there some reading somewhere that can guide me through the process of decoding it?
[Edit] The more I looked into it, the more I suspect the data to be BSON and not JSON, that would explain why I can read some bit of it but not everything. Any chance someone manage to decode BSON from a packet ?
How does the library know which packet decoder to use?
It starts at Layer 2 of the TCP/IP stack by identifying which protocol is used https://github.com/node-pcap/node_pcap/blob/master/decode/pcap_packet.js#L29-L56
switch (this.link_type) {
case "LINKTYPE_ETHERNET":
this.payload = new EthernetPacket(this.emitter).decode(buf, 0);
break;
case "LINKTYPE_NULL":
this.payload = new NullPacket(this.emitter).decode(buf, 0);
break;
case "LINKTYPE_RAW":
this.payload = new Ipv4(this.emitter).decode(buf, 0);
break;
case "LINKTYPE_IEEE802_11_RADIO":
this.payload = new RadioPacket(this.emitter).decode(buf, 0);
break;
case "LINKTYPE_LINUX_SLL":
this.payload = new SLLPacket(this.emitter).decode(buf, 0);
break;
default:
console.log("node_pcap: PcapPacket.decode - Don't yet know how to decode link type " + this.link_type);
}
Then it goes upper and tries to decode the proper protocol based on the flags it finds in the header https://github.com/node-pcap/node_pcap/blob/master/decode/ipv4.js#L12-L17 in this particular case for the IPv4 protocol
IPFlags.prototype.decode = function (raw_flags) {
this.reserved = Boolean((raw_flags & 0x80) >> 7);
this.doNotFragment = Boolean((raw_flags & 0x40) > 0);
this.moreFragments = Boolean((raw_flags & 0x20) > 0);
return this;
};
Then in your case it would match with the udp protocol https://github.com/node-pcap/node_pcap/blob/master/decode/ip_protocols.js#L15
protocols[17] = require("./udp");
Hence, If you check https://github.com/node-pcap/node_pcap/blob/master/decode/udp.js#L32 the packet is automatically decoded and it exposes a toString method
UDP.prototype.toString = function () {
var ret = "UDP " + this.sport + "->" + this.dport + " len " + this.length;
if (this.sport === 53 || this.dport === 53) {
ret += (new DNS().decode(this.data, 0, this.data.length).toString());
}
return ret;
};
What does this mean for you?
In order to decode a udp(any) packet you just call the high level api pcap.decode.packet(raw_packet) and then call toString method to display the decoded body payload
pcap_session.on('packet', function (raw_packet) {
let packet = pcap.decode.packet(raw_packet);
console.log(packet.toString());
});

dispatch queue causing sigabrt after a loop ends

I am getting a strange crash. I am writing data on bluetooth device. when the loop ends the app gets SIGABRT. I am not able to figure out the crash till now. Could someone help me to fix this ?
The app crashes in this function if the loop is called 2 times and it does not crash if it called 1 time.
BOOL success = [strongSelf.CronoDeviceObject.deviceHandler writeSettingsScreenData:data module:strongSelf.CronoDeviceObject.moduleNumber];
#pragma mark Button Save and cancel
- (IBAction)OkTaped:(id)sender{
//for submit
if ([self validateData]) {
[[ProgressHUD defaultHUD] setLoadingText:CVLocalizedString(#"Updating",nil)];
[[ProgressHUD defaultHUD]showInView:self.view];
[self performSelector:#selector(saveAllSettings) withObject:nil afterDelay:1.0];
}
}
- (void)saveAllSettings {
__weak __typeof__(self) weakSelf = self;
dispatch_queue_t queue = dispatch_queue_create("writesettings",NULL);
dispatch_async(queue, ^{
__strong __typeof__(self) strongSelf = weakSelf;
if (strongSelf.CronoDeviceObject) {
[strongSelf.CronoDeviceObject.deviceHandler writeFastWindUp:strongSelf.CronoDeviceObject.moduleNumber];
[strongSelf.CronoDeviceObject.deviceHandler writeLightOnOff:strongSelf.CronoDeviceObject.moduleNumber state:strongSelf.btnCheckBox2.selected?0x01:0x00];
strongSelf.CronoDeviceObject.lightState = (strongSelf.btnCheckBox2.selected)?0:1;
NSLog(#"Button Light is %#",([strongSelf.CronoDeviceObject isEnergySavingMode])?#"ON":#"Off");
NSString* semicolon =[NSString stringWithFormat:#";%#;%#;%#",strongSelf.BrandNametxtfld.text,strongSelf.ModalNametxtfld.text,[NSString stringWithFormat:#"%#;", strongSelf.WatchWinderNametxtfld.text]];
NSMutableData* data = [[NSMutableData alloc] initWithData:[semicolon dataUsingEncoding:NSUTF8StringEncoding]];
if ([strongSelf.CronoDeviceObject.deviceHandler respondsToSelector:#selector(writeSettingsScreenData:module:)]) {
BOOL success = [strongSelf.CronoDeviceObject.deviceHandler writeSettingsScreenData:data module:strongSelf.CronoDeviceObject.moduleNumber];
**//The app does not get here if the above function loop called 2 times but if it called 1 time it's working fine.**
if (success) {
dispatch_async(dispatch_get_main_queue(), ^{
__strong __typeof__(self) strongSelf = weakSelf;
self.CronoDeviceObject.Devicemodal.Brandname = strongSelf.BrandNametxtfld.text;
self.CronoDeviceObject.Devicemodal.modalName = strongSelf.ModalNametxtfld.text;
self.CronoDeviceObject.Devicemodal.winderName = strongSelf.WatchWinderNametxtfld.text;
// Update the UI
[[ProgressHUD defaultHUD]hideActivityIndicator];
[strongSelf.navigationController popViewControllerAnimated:YES];
});
}
}
}
});
}
- (BOOL) writeSettingsScreenData:(NSMutableData*) payload module:(Byte) module {
if (payload == nil) {
return false;
}
int numwrites = 1;
numwrites += (payload.length - 1)/32;
numwrites = (numwrites>8)?8:numwrites;
for(int i = 0; i < numwrites; i++){
//#try {
NSUInteger bufferLength = (payload.length - i*32);
Byte buff[32];
memset(buff, 0, 32);
[payload getBytes:&buff range:NSMakeRange(i*32, bufferLength)];
self.finalString = #"";
//rcvbuff = new StringBuffer(32);
self.chronoVisionMessage = [ChronoVisionMessage new];
//Set Line Address And Dir(R)
// chronoVisionMessage.setLineAddr(ChronoVisionMessage.LINE_BROADCAST);
// chronoVisionMessage.setLineDir(ChronoVisionMessage.LINE_WRITE);
//Set Module (communicnMstr/Address)
[self.chronoVisionMessage setModRsvd:(MODULE_BUSMASTER)];//set to 0
[self.chronoVisionMessage setModCh:(MODULE_BUSMASTER)];//set to default zero
if (module == 0) {
[self.chronoVisionMessage setModAddr:(MODULE_BROADCAST)];
}
else{
[self.chronoVisionMessage setModAddr:module];
}
//Set Register Access(R)/Addresss
[self.chronoVisionMessage setRegRw:REIGSTER_WRITE];
[self.chronoVisionMessage setRegType:REIGSTER_ACCESSTYPE1];//Access standard reg
[self.chronoVisionMessage setRegAddr:REIGSTER_ACCESSTYPE0];//set to 0
//[self.chronoVisionMessage setValueHi:REIGSTER_ACCESSTYPE0];//set to 0
[self.chronoVisionMessage setValueLo:((Byte)i)];//set to 0 to 7
[self.chronoVisionMessage setNewData:[NSMutableData dataWithBytes:buff length:32]];//set to 0
#try {
NSMutableData* header = [self.chronoVisionMessage getMessage];
NSMutableData* final = [[NSMutableData alloc] initWithBytes:[header bytes] length:[header length]];
[final appendBytes:buff length:32];
[self writeData:final];
int retryCount = 0;
while (!self.allDataReceived && retryCount<kTimeout) {
[NSThread sleepForTimeInterval:0.1];
}
//String allData = read(5000);
if(self.finalString.length == 0){
//_peripheral.setListener(null);
return false;
}
if ([self.finalString length] >= 8 && [self.finalString rangeOfString:#"\r"].location > 0) {
self.finalString = [self.finalString substringWithRange:NSMakeRange(0, [self.finalString rangeOfString:#"\r"].location)];
}
NSData *finalData = [self.finalString dataFromHex];
NSLog(#"final readBuff is %#",finalData);
if (i==(numwrites-1) && finalData.length >= 36) {
return true;
}
//free(buff);
}
#catch (NSException *exception) {
NSLog(#"Exception occured when writing user data %#",[exception description]);
}
}
return false;
}
here is an image after the crash
here is the back trace log
bt
* thread #12: tid = 0x13cf99, 0x3611c9aa libsystem_c.dylib`__abort + 102, queue = 'com.apple.root.default-qos', stop reason = EXC_BREAKPOINT (code=EXC_ARM_BREAKPOINT, subcode=0xdefe)
* frame #0: 0x3611c9aa libsystem_c.dylib`__abort + 102
frame #1: 0x3611cf94 libsystem_c.dylib`__stack_chk_fail + 180
frame #2: 0x0007a2d4 Chronovision`-[DeviceHandler writeSettingsScreenData:module:](self=0x17081990, _cmd=0x001069c2, payload=0x00000000, module='\x02') + 3028 at DeviceHandler.m:435
frame #3: 0x000d1f2c Chronovision`__34-[CVDetailViewController OkTaped:]_block_invoke(.block_descriptor=<unavailable>) + 400 at CVDetailViewController.m:357
frame #4: 0x002b219a libdispatch.dylib`_dispatch_call_block_and_release + 10
frame #5: 0x002bcc48 libdispatch.dylib`_dispatch_root_queue_drain + 1596
frame #6: 0x002bde20 libdispatch.dylib`_dispatch_worker_thread3 + 108
frame #7: 0x361fada8 libsystem_pthread.dylib`_pthread_wqthread + 668
(lldb)
Update
I ran the app in xcode 7.1.1 and I got the following log in console when the app crashes.
Dec 7 16:55:09 Rahuls-iPad Chronovision[1650] <Error>: ================================================================
==1650==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x088e06a0 at pc 0x0036f4a9 bp 0x088e02c4 sp 0x088dfe94
WRITE of size 42 at 0x088e06a0 thread T23
#0 0x36f4a7 in wrap_memmove (/private/var/mobile/Containers/Bundle/Application/33337E25-C69D-49F5-ABA1-5AD65673725C/Chronovision.app/Frameworks/libclang_rt.asan_ios_dynamic.dylib+0x2a4a7)
#1 0x287936b3 in <redacted> (/System/Library/Frameworks/Foundation.framework/Foundation+0x236b3)
#2 0x8a971 in -[DeviceHandler writeSettingsScreenData:module:] (/private/var/mobile/Containers/Bundle/Application/33337E25-C69D-49F5-ABA1-5AD65673725C/Chronovision.app/Chronovision+0x2d971)
#3 0x139eaf in __41-[CVDetailViewController saveAllSettings]_block_invoke (/private/var/mobile/Containers/Bundle/Application/33337E25-C69D-49F5-ABA1-5AD65673725C/Chronovision.app/Chronovision+0xdceaf)
#4 0x374e15 in __wrap_dispatch_async_block_invoke (/private/var/mobile/Containers/Bundle/Application/33337E25-C69D-49F5-ABA1-5AD65673725C/Chronovision.app/Frameworks/libclang_rt.asan_ios_dynamic.dylib+0x2fe15)
#5 0x853199 in _dispatch_call_block_and_release (/usr/lib/system/introspection/libdispatch.dylib+0x1199)
#6 0x85bd87 in _dispatch_queue_drain (/usr/lib/system/introspection/libdispatch.dylib+0x9d87)
#7 0x855ac3 in _dispatch_queue_invoke (/usr/lib/system/introspection/libdispatch.dylib+0x3ac3)
#8 0x85db19 in _dispatch_root_queue_drain (/usr/lib/system/introspection/libdispatch.dylib+0xbb19)
#9 0x85ee1f in _dispatch_worker_thread3 (/usr/lib/system/introspection/libdispatch.dylib+0xce1f)
#10 0x361fada7 in _pthread_wqthread (/usr/lib/system/libsystem_pthread.dylib+0xda7)
#11 0x361faafb in start_wqthread (/usr/lib/system/libsystem_pthread.dylib+0xafb)
Address 0x088e06a0 is located in stack of thread T23 at offset 128 in frame
#0 0x8a427 in -[DeviceHandler writeSettingsScreenData:module:] (/private/var/mobile/Containers/Bundle/Application/33337E25-C69D-49F5-ABA1-5AD65673725C/Chronovision.app/Chronovision+0x2d427)
This frame has 12 object(s):
[16, 24) 'r.i1'
[48, 56) 'r.i'
[80, 84) ''
[96, 128) 'buff'
[160, 168) '' <== Memory access at offset 128 partially underflows this variable
[192, 196) 'header'
[208, 212) 'final'
[224, 232) ''
[256, 264) ''
[288, 296) ''
[320, 324) 'finalData'
[336, 340) 'exception'
HINT: this may be a false positive if your program uses some custom stack unwind mechanism or swapcontext
(longjmp and C++ exceptions *are* supported)
Thread T23 created by T0 here:
<empty stack>
SUMMARY: AddressSanitizer: stack-buffer-overflow ??:0 wrap_memmove
Shadow bytes around the buggy address:
0x4111c080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c0a0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c0b0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c0c0: 00 00 00 00 f1 f1 00 f2 f2 f2 00 f2 f2 f2 04 f2
=>0x4111c0d0: 00 00 00 00[f2]f2 f2 f2 00 f2 f2 f2 04 f2 04 f2
0x4111c0e0: 00 f2 f2 f2 00 f2 f2 f2 00 f2 f2 f2 04 f2 04 f3
0x4111c0f0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c100: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c110: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
0x4111c120: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Heap right redzone: fb
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack partial redzone: f4
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
==1650==ABORTING
I got the problem with xcode 7.1.1.
I don't know why xcode 6.2 was unable to detect the crash location.
The problem was in the range I was using in the function
- (BOOL) writeSettingsScreenData:(NSMutableData*) payload module:(Byte) module {
if (payload == nil) {
return false;
}
int numwrites = 1;
numwrites += (payload.length - 1)/32;
numwrites = (numwrites>8)?8:numwrites;
for(int i = 0; i < numwrites; i++){
//#try {
//Changed this
NSUInteger bufferLength = (payload.length - i*32);
Byte buff[32];
memset(buff, 0, 32);
[payload getBytes:&buff range:NSMakeRange(i*32, bufferLength)];
//To this
NSUInteger bufferLength = ((payload.length - i*32)>32)?32:(payload.length-i*32);
Byte buff[32];
memset(buff, 0, 32);
if (payload && payload.length > bufferLength) {
[payload getBytes:&buff range:NSMakeRange(i*32, bufferLength)];
}
self.finalString = #"";
//rcvbuff = new StringBuffer(32);
self.chronoVisionMessage = [ChronoVisionMessage new];
//Set Line Address And Dir(R)
// chronoVisionMessage.setLineAddr(ChronoVisionMessage.LINE_BROADCAST);
// chronoVisionMessage.setLineDir(ChronoVisionMessage.LINE_WRITE);
//Set Module (communicnMstr/Address)
[self.chronoVisionMessage setModRsvd:(MODULE_BUSMASTER)];//set to 0
[self.chronoVisionMessage setModCh:(MODULE_BUSMASTER)];//set to default zero
if (module == 0) {
[self.chronoVisionMessage setModAddr:(MODULE_BROADCAST)];
}
else{
[self.chronoVisionMessage setModAddr:module];
}
//Set Register Access(R)/Addresss
[self.chronoVisionMessage setRegRw:REIGSTER_WRITE];
[self.chronoVisionMessage setRegType:REIGSTER_ACCESSTYPE1];//Access standard reg
[self.chronoVisionMessage setRegAddr:REIGSTER_ACCESSTYPE0];//set to 0
//[self.chronoVisionMessage setValueHi:REIGSTER_ACCESSTYPE0];//set to 0
[self.chronoVisionMessage setValueLo:((Byte)i)];//set to 0 to 7
[self.chronoVisionMessage setNewData:[NSMutableData dataWithBytes:buff length:32]];//set to 0
#try {
NSMutableData* header = [self.chronoVisionMessage getMessage];
NSMutableData* final = [[NSMutableData alloc] initWithBytes:[header bytes] length:[header length]];
[final appendBytes:buff length:32];
[self writeData:final];
int retryCount = 0;
while (!self.allDataReceived && retryCount<kTimeout) {
[NSThread sleepForTimeInterval:0.1];
}
//String allData = read(5000);
if(self.finalString.length == 0){
//_peripheral.setListener(null);
return false;
}
if ([self.finalString length] >= 8 && [self.finalString rangeOfString:#"\r"].location > 0) {
self.finalString = [self.finalString substringWithRange:NSMakeRange(0, [self.finalString rangeOfString:#"\r"].location)];
}
NSData *finalData = [self.finalString dataFromHex];
NSLog(#"final readBuff is %#",finalData);
if (i==(numwrites-1) && finalData.length >= 36) {
return true;
}
//free(buff);
}
#catch (NSException *exception) {
NSLog(#"Exception occured when writing user data %#",[exception description]);
}
}
return false;
}

Forging or Building packets in NodeJS

I have to send a packet, when viewed in hex is:
0A 00 2C 01 23 00 0C 00 B3 01
0A 00 is the length which is 10.
2C 01 is a identifier 12c or could be a decimal packet id.
23 00 is a version of dec 35.
0C 00 is another version which is dec 12.
b3 01 is 435.
which is from different variables and configs.
var packet_id = 300;
var game_version = config.game.version; // 35 from config
var update_version = config.update.version; // 12 from config
var date_version = config.date.version; // 435 from version
The length is then calculated from the size with the length. Then build this buffer and send it..
But how do I do this? I also was thinking that I want to predefine packet structure and just enter parameters like:
packet("versionCheck", // name of packet structure (defined somewhere
300 , // the packet id on the structure
config.game.version, // the 2nd parameter for the versionCheck structure.....
............
I am trying to use the packet package by bigeasy for node but I can only make it work with Parsing, not with Building packets.
That's actually a pretty basic example of packet, since everything is static. Something like this might work:
function Packet (length, id, v1, v2, other) {
this._length = length;
this._id = id;
this._v1 = v1;
this._v2 = v2;
this._other = other;
}
Packet.prototype.toBuffer = function () {
var buffer = new Buffer(this._length);
buffer.writeUInt16LE(this._length, 0);
buffer.writeUInt16LE(this._id, 2);
buffer.writeUInt16LE(this._v1, 4);
buffer.writeUInt16LE(this._v2, 6);
buffer.writeUInt16LE(this._other, 8);
return buffer;
}
var packet = new Packet(10, 0x12c, 35, 12, 435);
console.log(packet.toBuffer());
Also for parsing you don't need anything special, just same as toBuffer, but with read instead of write methods

Resources