2

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
E.Arrowood
  • 750
  • 7
  • 17
  • 1
    Would this be an adequate re-question? "Convert a hex string to raw binary buffer". If so, what's insufficient with `from(..., 'hex')`? If not, what's insufficient with `from(...,'hex')`? – user2864740 May 12 '20 at 00:16
  • great question, how do I get node.js to output the raw binary buffer? is that possible? – E.Arrowood May 12 '20 at 00:18
  • Maybe https://stackoverflow.com/a/35455728/2864740 ? That is, use a stream method that accepts a Buffer directly (no to/from-string conversions). – user2864740 May 12 '20 at 00:19
  • hmm. okay let me see if I can get this to work. its very tricky to transform a buffer to a write stream but i know it is possible – E.Arrowood May 12 '20 at 00:20
  • 1
    Ooh its not actually as hard as i thought: node -p "process.stdout.write(Buffer.from('e13adbea5d743c30b8ea0edd0337b924c6bd0a78', 'hex'))" | hexdump -C – E.Arrowood May 12 '20 at 00:22
  • 1
    Thank you! I think I have an answer to this now, need to confirm with my code though – E.Arrowood May 12 '20 at 00:23

1 Answers1

0

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
E.Arrowood
  • 750
  • 7
  • 17