最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - split binary data into array or classes in node.js - Stack Overflow

programmeradmin0浏览0评论

How can I split a buffer of binary data in Node.js by a binary delimiter? For example, a socket data is sent with binary code with each field dilimited by \xb8. How can I split that into an array?

Better yet, is there some way to write a class or something that it can be loaded into? For example, each packet sends mand-argument pairs delimited by \xb8. Is there anyway I can take a variable with binary data and break into multiple Command instances?

How can I split a buffer of binary data in Node.js by a binary delimiter? For example, a socket data is sent with binary code with each field dilimited by \xb8. How can I split that into an array?

Better yet, is there some way to write a class or something that it can be loaded into? For example, each packet sends mand-argument pairs delimited by \xb8. Is there anyway I can take a variable with binary data and break into multiple Command instances?

Share Improve this question edited Jan 19, 2012 at 5:25 Mot 29.6k24 gold badges86 silver badges122 bronze badges asked Jan 19, 2012 at 2:23 LordZardeckLordZardeck 8,28319 gold badges65 silver badges119 bronze badges 3
  • Are you having trouble with simply iterating over the buffer looking for \xb8? – loganfsmyth Commented Jan 19, 2012 at 3:24
  • I don't know how to do anything binary with NodeJS. – LordZardeck Commented Jan 19, 2012 at 3:54
  • True enough. Just remember, hex isn't magic. You can just as easily loop over everything and pare it with 216 instead of 0xD8 since they are the same. – loganfsmyth Commented Jan 19, 2012 at 15:04
Add a ment  | 

2 Answers 2

Reset to default 6

Read the Buffers documentation.

Iterate through each character in the buffer and create a new buffer whenever you encounter the specified character.

function splitBuffer(buf, delimiter) {
  var arr = [], p = 0;

  for (var i = 0, l = buf.length; i < l; i++) {
    if (buf[i] !== delimiter) continue;
    if (i === 0) {
      p = 1;
      continue; // skip if it's at the start of buffer
    }
    arr.push(buf.slice(p, i));
    p = i + 1;
  }

  // add final part
  if (p < l) {
    arr.push(buf.slice(p, l));
  }

  return arr;
}

binary code with each field dilimited by \xb8. How can I split that into an array?

Using iter-ops library, we can process a buffer as an iterable object:

import {pipe, split} from 'iter-ops';

const i = pipe(buffer, split(v => v === 0xb8));

console.log([...i]); // your arrays of data
发布评论

评论列表(0)

  1. 暂无评论