Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert to buffer in node.js? #34

Closed
coolaj86 opened this issue Jul 22, 2016 · 3 comments
Closed

How to convert to buffer in node.js? #34

coolaj86 opened this issue Jul 22, 2016 · 3 comments

Comments

@coolaj86
Copy link

coolaj86 commented Jul 22, 2016

I need to take a long (from protobufjs) and convert it to base64 using node.js' Buffer... can you add the one-liner to an examples section or something?

I'm just a little confused as to how to do it and, unfortunately, I don't have a reference byte sequence with corresponding base64 string for what I'm working on so trial and error is... confusing... :-/

I was expecting something like

Buffer.from([l.high, l.low]).toString('base64');

but that didn't yield valid values.

@dcodeIO
Copy link
Owner

dcodeIO commented Jul 22, 2016

The low and highproperties hold the low respectively high 32 bits of the 64 bit long. Buffer.from, in your case, expects an array of octets.

var buf = Buffer.alloc(8);

// BE
  buf.writeInt32BE(l.high, 0);
  buf.writeInt32BE(l.low, 4);

// or LE
  buf.writeInt32LE(l.low, 0);
  buf.writeInt32LE(l.high, 4);

console.log(buf.toString("base64"));

dcodeIO added a commit that referenced this issue Jul 22, 2016
@coolaj86
Copy link
Author

Thanks! :)

Regarding LE/BE... since this is dependent on the architecture of the chip, does protobuf specify which order the bytes are in? Might I assume that a sane developer would choose "network order", that being BE, right?

I'll have to google a little bit. I'm confused as to why node doesn't have a whatever-my-cpu-wants option...

@dcodeIO
Copy link
Owner

dcodeIO commented Jul 23, 2016

protobuf always uses LE. Generally spoken, with JavaScript you always have to specify byte order explicitly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants