packetie
packetie

Reputation: 5069

node.js convert binary string to number

Writing a node.js application, it receives from a socket a binary string of 4 bytes "\x00\x00\x00\x13", I need to convert it to integer (19 which is 0x13 in our case) using big endian order.

In other scripting languages, like perl, we can do unpack. unpack("N", )

In node.js, not sure how do do it.

Upvotes: 3

Views: 1653

Answers (2)

alex
alex

Reputation: 12265

new Buffer('\x00\x00\x00\x13', 'binary').readInt32BE(0)

Upvotes: 4

jlents
jlents

Reputation: 820

npm is your friend here. The module anybase looks like it might be up to the task. Here's a link for more info: https://www.npmjs.org/package/anybase

Future tip:
you can search npm from the commandline and probably find a module for most common things.
The syntax is like this:

npm search string1 string2 string3

And it will match any module that has all the strings listed. This following command led me to anybase:

npm search binary convert

I hope this helps.

Upvotes: 0

Related Questions