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
2
  • 2
    For clarity, please give examples of input and desired output(s). Jun 3, 2022 at 8:36
  • @PhilHudson Good idea, added! Jun 3, 2022 at 17:52

1 Answer 1

5
(defun hexify-string (strg)
  (mapconcat (lambda (c) (format "%x" c)) strg ""))
3
  • Great, thanks. Was sure there will be an elegant solution. Will delete my answer. Jun 3, 2022 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. Jun 3, 2022 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 gnu.org/software/emacs/manual/html_node/elisp/… So for UTF8 the string would be "%o"? That didn't seem to work, I still got the utf16 be encoding. Jun 3, 2022 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.