2

I did my homework before, so i'm aware of other questions like pack / unpack functions for node.js

the point is, those packs, return everything but a binary string. What i would like to do is a simple:

ruby-1.9.2-p136 :001 > [1,"10.0.0.1","foo"].pack 'l! a4 Z*'
 => "\x01\x00\x00\x00\x00\x00\x00\x0010.0foo\x00" 
Community
  • 1
  • 1
VP.
  • 5,122
  • 6
  • 46
  • 71
  • Can you explain the intent of your example? It is very specific and unclear why you would do this - you pack the number 1 as a native-endian signed long, four bytes of the string "10.0.0.1", and the string "foo" null terminated. Or are you just looking for a general purpose "pack/unpack" library like in Ruby? – maerics Jun 22 '11 at 13:33
  • a generate a binary string that will be mapped to a C struct. the ruby code works, i can exchange information through a svipc between my ruby (perl, python as well) code and my C code. but with javascript, it doesn't work. – VP. Jun 22 '11 at 13:46

2 Answers2

2

In node.js v0.5.0-pre Buffers have various "write" methods which include explicit signedness and endianness.

So your example would be transliterated from Ruby to node.js JavaScript like:

var b = new Buffer(8/*long*/ + 4 + 4);
b.writeInt32(1/*value*/, 0/*offset*/, 'little'/*endian*/);
b.write('10.0', 8/*offset*/);
b.write('foo\0', 12/*offset*/);
b.toString();
// => '\u0001\u0000\u0000\u0000\u0000\u0000\u0000\u000010.0foo\u0000'

[Edit]: Updated the link to the Buffers documentation directly in the GitHub repository.

maerics
  • 151,642
  • 46
  • 269
  • 291
-2

Using JS, use the myVar.toString(2) where 2 is the radix. This will return a binary value in 1's and 0's.

Joseph Lust
  • 19,340
  • 7
  • 85
  • 83