lisp decoding?
how to decode a binary stream in lisp i did with with-open -file and passing a argument as element-type '(unsigned byte 8) but returning as numbers not 开发者_如何学Ca string please help me on this problem
;;; Flexi-Streams "bivalent streams" solve the binary vs. character stream problem.
;;; You'll want to install QuickLisp and understand the REPL * and ** variables:
(require 'flexi-streams) ;; or (ql:quickload 'flexi-streams)
(with-open-file (out "foo.text" :direction :output)
(write-line "Foo" out)) ; "Foo"
(with-open-file (in "foo.text")
(read-line in)) ; "Foo", NIL
(with-open-file (in "foo.text" :element-type '(unsigned-byte 8))
(read-line in)) ;; read-line wrong stream type error
(with-open-file (in "foo.text" :element-type '(unsigned-byte 8))
(let ((s (make-array 3)))
(read-sequence s in) s)) ; #(70 111 111)
(map 'list #'code-char *) ; (#\F #\o #\o)
(map 'string #'code-char **) ; "Foo"
(with-open-file (raw "foo.text" :element-type 'flexi-streams:octet)
(with-open-stream (in (flexi-streams:make-flexi-stream raw))
(read-line in))) ; "Foo", NIL
;; Thanks to Edi Weitz for providing this essential tool.
Your problem is not a problem, I think. When you open a file in binary mode as unsigned-byte 8, you are specifying to read the file, 8 bits as a time, represented as a number from 0 to 255. Depending on how you read it, you might get it as an ARRAY or a LIST.
A 'text' file is a set of numbers using the ASCII representation of characters. For more sophisticated text, Unicode representation is used, but that is closer to a traditional binary format than a text one.
If you attempt to read a PDF file, you will have to follow the file format to gain meaningful data from it. Wotsit's site has a library of file formats.
From your question, it sounds as if you are just learning programming. I don't recommend working with PDFs when you are just learning.
The question is a bit unclear. I think your problem is that you have created a file that you have written one (or more) elements of type (unsigned-byte 8)
, but when you try to read it you are getting characters, not binary values.
If that is the case, you will need to open the file with :element-type '(unsigned-byte 8)
.
If I have misunderstood what you want, please edit your question and I shall try to answer your question.
The short answer is that you don't need to specify the :element-type
if you want to read in strings.
The type '(unsigned-byte 8)
refers to a number, not to chars as in C. In Lisp, character is an actual datatype and you would need to open the file with this element type to get strings. The important thing to realize is that :element-type
determines what data type elements in the file will be parsed into and returned as. If you read the hyperspec page on open you see that element-type has to either be a subtype of character, integer, or be unsigned-byte or signed-byte. The default, however, is character, which produces strings in whatever format your lisp uses.
精彩评论