How do I encode a string of hexadecimal digits using javascript? (replicating ruby array.pack('H'))

Viewed 150

I'm trying to replicate this ruby script using JavaScript and Node.js:

$ ruby -e "STDOUT.write ['e13adbea5d743c30b8ea0edd0337b924c6bd0a78'].pack('H40')"

There was an earlier piece where I converted ['hello'].pack('Z*') to Buffer.from('hello\0'), but this other part is driving me insane.

I've found the source code for this in Ruby: https://github.com/ruby/ruby/blob/9e41a75255d15765648279629fd3134cae076398/pack.c#L426 but i don't understand C very well, let alone bit shifting in C.

I read through this Stack Exchange question and answer but still couldn't figure anything out (https://codereview.stackexchange.com/questions/3569/pack-and-unpack-bytes-to-strings)

Any insight here would be much appreciated.

Furthermore, the best answer here would be something that I could run with node -p and pipe to hexdump -C to get the exact same output of Ruby.

i.e.

$ ruby -e "STDOUT.write ['e13adbea5d743c30b8ea0edd0337b924c6bd0a78'].pack('H40')" | hexdump -C

00000000  e1 3a db ea 5d 74 3c 30  b8 ea 0e dd 03 37 b9 24  |.:..]t<0.....7.$|
00000010  c6 bd 0a 78                                       |...x|
00000014

The closes I got was with:

node -p "Buffer.from('e13adbea5d743c30b8ea0edd0337b924c6bd0a78', 'hex').toString('utf8')" | hexdump -C

00000000  ef bf bd 3a ef bf bd ef  bf bd 5d 74 3c 30 ef bf  |...:......]t<0..|
00000010  bd ef bf bd 0e ef bf bd  03 37 ef bf bd 24 c6 bd  |.........7...$..|
00000020  0a 78 0a                                          |.x.|
00000023
1 Answers

The solution for me was that I actually was already converting a hex string to a raw binary buffer, except I wasn't realizing it because I wasn't printing it out correctly.

The working script is:

$ node -e "process.stdout.write(Buffer.from('e13adbea5d743c30b8ea0edd0337b924c6bd0a78', 'hex'))" | hexdump -C
Related