Skip to content

Integers

j3pic edited this page Feb 17, 2022 · 6 revisions

Integer types

Lisp-Binary supports reading and writing of unsigned-byte and signed-byte integer types. Their Lisp-Binary type designators are similar to their Common Lisp equivalents:

(unsigned-byte <bits>)
(signed-byte <bits> &key (signed-representation :twos-complement))

The number of bits can be anything. Lisp-Binary will generate code that reads exactly that number of bits, using special techniques to accomplish this if the number of bits implies reading part of a byte. For extremely large numbers of bits, encoding and decoding may be slow, but this may depend on your Common Lisp implementation's bignum implementation. The algorithms used for reading and writing are:

Read:

  1. Read the bits as a byte array using lisp-binary:read-bytes.
  2. Encode these into a Lisp integer using shifting and masking.

Write:

  1. Use shifting and masking to split a Lisp integer into a byte array.
  2. Write the bytes using lisp-binary:write-bytes.

The signed-byte type has a :signed-representation argument that defaults to :twos-complement, the most common signed representation used in binary formats. :ones-complement is also supported.

Lisp-Binary generates calls to read-integer and write-integer to handle integer types. These are documented below:

read-integer

(read-integer length stream &key (byte-order :little-endian) signed (signed-representation :twos-complement))

Reads an integer of length bytes from the stream in the specified byte-order.

If signed is non-NIL, the :signed-representation can be either :twos-complement (the default) or :ones-complement.

If the stream is a bit-stream, then the length can be a rational number (1/8 of a byte = 1 bit).

write-integer

(write-integer number size stream &key (byte-order :little-endian) signed (signed-representation :twos-complement))

Writes the number of size bytes to the stream.