Skip to main content

byte, byte-size, byte-position

byte, byte-size, byte-position Function

Syntax:

byte size position → bytespec

byte-size bytespec → size

byte-position bytespec → position

Arguments and Values:

size, position—a non-negative integer .

bytespec—a byte specifier .

Description:

byte returns a byte specifier that indicates a byte of width size and whose bits have weights 2position+size−1through 2position, and whose representation is implementation-dependent.

byte-size returns the number of bits specified by bytespec.

byte-position returns the position specified by bytespec.

Examples:

(setq b (byte 100 200)) → #<BYTE-SPECIFIER size 100 position 200> 
(byte-size b)100
(byte-position b)200

See Also:

ldb, dpb

Notes:

(byte-size (byte j k)) ≡ j

(byte-position (byte j k)) ≡ k

A byte of size of 0 is permissible; it refers to a byte of width zero. For example,

(ldb (byte 0 3) #o7777) → 0

(dpb #o7777 (byte 0 3) 0) → 0

Expanded Reference: byte, byte-size, byte-position

Creating byte specifiers

byte creates a byte specifier describing a contiguous field of bits with a given size (width) and position (starting bit).

;; A 4-bit field starting at bit 0 (the low nibble)
(byte 4 0)
;; => impl-dependent

;; An 8-bit field starting at bit 8 (the second byte)
(byte 8 8)
;; => impl-dependent

Querying byte specifier properties

byte-size returns the width and byte-position returns the starting bit of a byte specifier.

(let ((bs (byte 100 200)))
(list (byte-size bs)
(byte-position bs)))
=> (100 200)

(byte-size (byte 4 0))
=> 4
(byte-position (byte 4 0))
=> 0

Using byte specifiers with ldb and dpb

Byte specifiers are typically used with ldb (load byte) and dpb (deposit byte).

;; Extract the low nibble (4 bits starting at position 0)
(ldb (byte 4 0) #xFF)
=> 15

;; Extract the high nibble (4 bits starting at position 4)
(ldb (byte 4 4) #xFF)
=> 15

;; Deposit the value 5 into the low nibble
(dpb 5 (byte 4 0) #xF0)
=> 245

Zero-width byte specifiers

A byte of size 0 is valid and always extracts or deposits zero.

(ldb (byte 0 3) #o7777)
=> 0
(dpb #o7777 (byte 0 3) 0)
=> 0

Practical use: extracting RGB components from a 24-bit color

(let ((color #x1A8844))
(list (ldb (byte 8 16) color)
(ldb (byte 8 8) color)
(ldb (byte 8 0) color)))
=> (26 136 68)