views:

194

answers:

1

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.

A: 

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
I rolled my own using basic string methods. It was embarrassingly simple. Hello, Javascript.
HappyCoder
@HappyCoder, any chance you could share your embarrassingly simple pack and unpack methods?
nohat
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