Lisp - Binary I/O



Binary I/O means reading/writing binary data from/to various types of data sources ranging from strings, files and standard input/output. In this chapter, we're discussing various concepts and functions relevant to binary I/O with example.

Binary Streams

In Lisp, we've streams for I/O operations. Streams are used to handle either character based data or binary data. Character Streams are used to read character text whereas binary streams are used to process raw bytes.

A binary Stream is crucial in handling binary files like images, audios or executable files.

Functions on Binary Streams

In Common LISP, we've following functions specifically designed for binary I/O.

Input Functions

  • read-byte− used to read a byte from a binary input stream.

  • read-sequence− used to read a sequence of bytes from a binary input stream into an array.

Output Functions

  • write-byte− used to write a single byte into a binary input stream.

  • write-sequence− used to read a sequence of bytes from a binary input stream into an array.

Handling File

A file is opened using open function. We need to specify :element-type to open function to specify that stream is to handle bytes. We can use '(unsigned-byte 8) to specify the binary stream will handle 8 bit unsigned integers.

We can also use with-open-file macro to open a fine. This macro closes file after use.

Example - Writing Binary File

; open binary-data.data in binary mode to write data
(with-open-file (stream "binary-data.dat"
   :direction :output
   :element-type '(unsigned-byte 8)
   :if-exists :supersede)
   (write-byte 255 stream) ; write 255
   (write-byte 0 stream))  ; write 0

Output

When you execute the code, it returns the following result −

0

Explanation

  • with-open-file macro is used to open stream for binary-data.dat in write mode as direction being output.

  • write-byte function is used to write two bytes to the file.

Example - Reading Binary File

; open binary-data.data in binary mode to read data
(with-open-file (stream "binary-data.dat"
   :direction :input
   :element-type '(unsigned-byte 8))
   (let ((byte1 (read-byte stream))
      (byte2 (read-byte stream)))
      (format t "Byte 1: ~d, Byte 2: ~d~%" byte1 byte2))) ; read bytes

Output

When you execute the code, it returns the following result −

Byte 1: 255, Byte 2: 0

Explanation

  • with-open-file macro is used to open stream for binary-data.dat in read mode as direction being input.

  • read-byte function is used to read bytes from the file.

Advertisements