Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert byte array to string in Common Lisp?

Tags:

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.

like image 978
Ken Avatar asked Mar 01 '09 16:03

Ken


1 Answers

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

like image 70
dmitry_vk Avatar answered Sep 27 '22 17:09

dmitry_vk