Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to specify :element-type for with-output-to-string

39 views
Skip to first unread message

Jim Newton

unread,
Feb 7, 2019, 4:56:13 PM2/7/19
to
I have opened a file with :element-type 'unsigned byte, and I want
to copy some of the bytes I read into as string, so I can read them
back out using a different :element-type.
How can I open the string with an element type for which I can call (write-byte string)
later?
When I try the following I get an error.

(with-output-to-string (string nil :element-type 'unsigned-byte)
nil)

UNSIGNED-BYTE is not a subtype of CHARACTER
[Condition of type SIMPLE-ERROR]

Restarts:
0: [RETRY] Retry SLIME REPL evaluation request.
1: [*ABORT] Return to SLIME's top level.
2: [ABORT] abort thread (#<THREAD "repl-thread" RUNNING {1002C48003}>)

Pascal J. Bourguignon

unread,
Feb 7, 2019, 7:53:40 PM2/7/19
to
It is not possible, since the interesection between the charcter type
and the unsigned-type is empty.

(eval-when (:compile-toplevel :load-toplevel :execute)
(ql:quickload :babel))

(with-open-file (binary-file "path.bin" :element-type '(unsigned-byte 8))
(with-output-to-string (output)
(let* ((code (read-byte binary-file))
(octets (vector code))
(string (babel:octets-to-string octets
:errorp nil
:encoding :iso-8859-1 #| or whatever encoding
you want to use to convert your binary data to characters |#)))
(write-string string output))))

--
__Pascal J. Bourguignon__
http://www.informatimago.com

tar...@google.com

unread,
Feb 11, 2019, 1:59:44 PM2/11/19
to
On Thursday, February 7, 2019 at 1:56:13 PM UTC-8, Jim Newton wrote:
> I have opened a file with :element-type 'unsigned byte, and I want
> to copy some of the bytes I read into as string, so I can read them
> back out using a different :element-type.

Perhaps you should use READ-SEQUENCE to read the data from the file into a
sequence with the element type 'unsigned-byte. You can then do various things
with that data, including extracting some of the bytes and converting them
to some different type.

Depending on what sort of type conversion you need to do, you may have to
handle the coercion yourself or else perhaps use the library Pascal suggested.

A simple example, where /tmp/foo.text contains
This is some data.

(defvar *buffer* (make-array 1000 :element-type 'unsigned-byte))
(with-open-file (f "/tmp/foo.text" :element-type 'unsigned-byte)
(read-sequence *buffer* f))
(with-output-to-string (s)
(write-sequence (map 'list #'code-char (subseq *buffer* 2 10)) s))
=> "is is da"
0 new messages