How to convert byte array to string in Common Lisp?

Ken picture Ken · Mar 1, 2009 · Viewed 10.9k times · Source

I'm calling a funny API that returns a byte array, but I want a text stream. Is there an easy way to get a text stream from a byte array? For now I just threw together:

(defun bytearray-to-string (bytes)
  (let ((str (make-string (length bytes))))
    (loop for byte across bytes
       for i from 0
       do (setf (aref str i) (code-char byte)))
    str))

and then wrap the result in with-input-from-string, but that can't be the best way. (Plus, it's horribly inefficient.)

In this case, I know it's always ASCII, so interpreting it as either ASCII or UTF-8 would be fine. I'm using Unicode-aware SBCL, but I'd prefer a portable (even ASCII-only) solution to a SBCL-Unicode-specific one.

Answer

dmitry_vk picture dmitry_vk · Mar 1, 2009

FLEXI-STREAMS (http://weitz.de/flexi-streams/) has portable conversion function

(flexi-streams:octets-to-string #(72 101 108 108 111) :external-format :utf-8)

=>

"Hello"

Or, if you want a stream:

(flexi-streams:make-flexi-stream
   (flexi-streams:make-in-memory-input-stream
      #(72 101 108 108 111))
   :external-format :utf-8)

will return a stream that reads the text from byte-vector