reddit / emacs

Best way to decode hexadecimal in Emacs Lisp?

ramin-honary-xc · 2022-02-13 19:44
So I have a chunk of hexadecimal digits in a buffer, I want to convert it to raw bytes. I happen to know the raw bytes are going to all be ASCII characters. Here is the solution I have so far: I start with this: 74686520717569636b2062726f776e20 666f78206a756d706564206f76657220 746865206c617a7920646f67 I run this on the buffer (let ((case-replace nil)) (replace-regexp "[[:xdigit:]]\\{2\\}" "\\\\x\\&") (goto-char (point-min)) (replace-regexp "^" "(insert \"") (goto-char (point-min)) (replace-regexp "$" "\")")) That makes the buffer into this: "\x74\x68\x65\x20\x71\x75\x69\x63\x6b\x20\x62\x72\x6f\x77\x6e\x20" "\x66\x6f\x78\x20\x6a\x75\x6d\x70\x65\x64\x20\x6f\x76\x65\x72\x20" "\x74\x68\x65\x20\x6c\x61\x7a\x79\x20\x64\x6f\x67" Now I make it into a Lisp expression: (goto-char (point-min)) (insert "(insert\n") (goto-char (point-max)) (insert ")") Now my buffer has this: (insert "\x74\x68\x65\x20\x71\x75\x69\x63\x6b\x20\x62\x72\x6f\x77\x6e\x20" "\x66\x6f\x78\x20\x6a\x75\x6d\x70\x65\x64\x20\x6f\x76\x65\x72\x20" "\x74\x68\x65\x20\x6c\x61\x7a\x79\x20\x64\x6f\x67") Finally I do this: (eval (read (prog1 (buffer-string) (erase-buffer)))) and I get the result I want the quick brown fox jumped over the lazy dog Is there a better way to do this? It would especially be nice to do this without `(eval (read (buffer-string)))`. Note that this function needs to run on arbitrary length string inputs scattered throughout a buffer, but mostly operate on only 2-8 bytes of hexadecimal encoded data at a time, so something that works efficiently on small strings is best. Thanks!
jinwoo68 · 2022-02-13 19:56
There's the `cl-parse-integer` function, which is like Common Lisp's `parse-integer`. ``` (cl-defun cl-parse-integer (string &key start end radix junk-allowed) ... ``` You'll be able to update `start` and `end` for each two digits with `radix` set to 16.
SlowValue · 2022-02-13 20:37
Have a look at the solutions posted to stackoverflow: https://stackoverflow.com/questions/12003231/how-do-i-convert-a-string-of-hex-into-ascii-using-elisp
ramin-honary-xc · 2022-02-14 06:01
I think `cl-parse-integer` is exactly the kind of thing I need. Actually, I could probably use `string-to-number` and achieve the same effect, which might be better since it is a built-in function. Thanks, this was very helpful!