4

What are the JavaScript functions or libraries that are equivalent to Ruby's pack and unpack functions for the Array class? I'm particularly interested in converting hex strings to strings.

irb(main):022:0> ["446f67"].pack("H*")
=> "Dog"

I'm not a JavaScript programmer and would rather not roll my own converter if libraries are available.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
HappyCoder
  • 73
  • 1
  • 7

2 Answers2

0

I don't think JavaScript has a function that does quite the same thing; pack seems to be a Ruby specific. If you're using pack to turn an object into a string, which can be sent over a network, you could use JSON instead. The Prototype library provides methods for turning objects into JSON-encoded strings. There are also Ruby libraries for working with JSON (encoding and decoding) such as:

http://flori.github.com/json/

allyourcode
  • 21,871
  • 18
  • 78
  • 106
  • I rolled my own using basic string methods. It was embarrassingly simple. Hello, Javascript. – HappyCoder Feb 12 '10 at 10:21
  • @HappyCoder, any chance you could share your embarrassingly simple pack and unpack methods? – nohat Sep 17 '10 at 23:22
  • function hex2string(hex) { i = 0; ascii = ""; while (i < hex.length/2) { ascii = ascii+String.fromCharCode(parseInt(hex.substr(i*2,2),16) ) ; i++; } return ascii; } Sorry for the late reply. Didn't see your query until now. I don't think I implemented the reverse in Javascript. Hope this code helps. – HappyCoder Oct 09 '10 at 21:24
0

answered here: pack / unpack functions for node.js

Community
  • 1
  • 1
Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75