Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js data parsing raw bytes with Buffer

I'm trying to use Buffer to parse 29 bytes of data that is formatted in odd ways. I've been using the slice() method to carve up the data on these odd boundaries. A sample stream looks like the following in hex (spaces added for clarity)...

01 1d 00 00 01 0a 0a 0b 0b 0c 0c 00 00 04 d2 00 00 00 0e c8 00 00 00 00 00 00 00 cc c4

var raw = '011d0000010a0a0b0b0c0c000004d20000000ec800000000000000ccc4';
buff = new Buffer(raw, 'utf8');
var position = 2;

// message type
var msg_type = buff.slice(position,(position+1)).toString();
position += 1;
console.log('... message type is ' + msg_type);

// event type
var event_type = buff.slice(position,(position+1)).toString();
position += 1;
console.log('... event type is ' + event_type);

// grab more data...

This produces an msg_type=1 and event_type=0. It should be 0 and 1, respectively. All of the slices that follow are wrong.

I'm clearly misunderstanding something with the encoding here. Either during Buffer instantiation or in the toString() extraction.

How can I treat this input stream as a series of hex strings and convert them into binary data that I can operate on?

Thanks!

like image 990
Greg Avatar asked Nov 08 '11 23:11

Greg


People also ask

How do I decode buffer data in node JS?

In Node. js, the Buffer. toString() method is used to decode or convert a buffer to a string, according to the specified character encoding type. Converting a buffer to a string is known as encoding, and converting a string to a buffer is known as decoding.

How does the buffer store data in node JS?

A buffer is a space in memory (typically RAM) that stores binary data. In Node. js, we can access these spaces of memory with the built-in Buffer class. Buffers store a sequence of integers, similar to an array in JavaScript.

How do you convert a buffer to a string value in node JS?

Buffers have a toString() method that you can use to convert the buffer to a string. By default, toString() converts the buffer to a string using UTF8 encoding. For example, if you create a buffer from a string using Buffer. from() , the toString() function gives you the original string back.

What does the BUF toJSON () method return in node JS?

The toJSON() method returns a JSON object based on the Buffer object.


1 Answers

Node's Buffer supports this directly with the hex encoding:

var raw = '011d0000010a0a0b0b0c0c000004d20000000ec800000000000000ccc4';
var buff = new Buffer(raw, 'hex');
like image 143
GraemeF Avatar answered Oct 03 '22 10:10

GraemeF