0

I somewhat routinely need to convert an arbitrarily long string to hex, usually encoded as ascii or unicode.

Is there a way to quickly and easily do this using vanilla Emacs? If not, is there a go to package that can do this?

There was a prior question about converting a single character to its hex value, but this question is interested in converting arbitrarily long strings to hex.

Examples ("input string" output hex):

  • "bird" 62697264
  • "What are we going to do tomorrow night? The same thing we do every night Pinky, try to take over the world!" 576861742061726520776520676f696e6720746f20646f20746f6d6f72726f77206e696768743f205468652073616d65207468696e6720776520646f206576657279206e696768742050696e6b792c2074727920746f2074616b65206f7665722074686520776f726c6421
  • "おはようございます"
    • (utf8) e3818ae381afe38288e38186e38194e38196e38184e381bee38199
    • (utf16 be) 304a306f30883046305430563044307e3059
holocronweaver
  • 1,319
  • 10
  • 22

1 Answers1

5
(defun hexify-string (strg)
  (mapconcat (lambda (c) (format "%x" c)) strg ""))
Phil Hudson
  • 1,651
  • 10
  • 13
  • Great, thanks. Was sure there will be an elegant solution. Will delete my answer. – Andreas Röhler Jun 03 '22 at 11:04
  • I appreciate the kind words and collaborative spirit. I did consider using `(apply-partially #'format "%x")`, which I think would be more elegant, but it's a couple of characters longer than `(lambda (c) (format "%x" c))` -- unless you use `-partial` from `dash.el` instead, which is what I would usually do in practice. – Phil Hudson Jun 03 '22 at 11:08
  • A simple custom solution! I guess to add other encodings you would have to add another parameter and map it to the appropriate format string from https://www.gnu.org/software/emacs/manual/html_node/elisp/Formatting-Strings.html So for UTF8 the string would be "%o"? That didn't seem to work, I still got the utf16 be encoding. – holocronweaver Jun 03 '22 at 23:37