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!