Search code examples
elisp

UTF-8 bytes to string


I'm trying to convert a list like '(110 111 101 204 136 108) to a string like "noël".

I tried using (mapcar (lambda (c) (decode-char 'unicode c)) '(110 111 101 204 136 108)), but it resulted in (110 111 101 204 136 108), the same as the input. (Also, I recognize that there's no way to decode a Unicode character from a single byte of UTF-8, so that's definitely the wrong function.)


Solution

  • A few options...

    (with-temp-buffer
      (set-buffer-multibyte nil)
      (apply #'insert '(110 111 101 204 136 108))
      (decode-coding-region (point-min) (point-max) 'utf-8 t))
    

    or:

    (decode-coding-string
     (mapconcat #'byte-to-string '(110 111 101 204 136 108) "")
     'utf-8)
    

    or more directly:

    (string-as-multibyte
      (apply #'unibyte-string '(110 111 101 204 136 108)))