ldb
ldb Accessor
Syntax:
ldb bytespec integer ! byte
(setf (ldb bytespec place**)** new-byte**)**
Pronunciation:
[ lidib ] or [ lidεb ] or [ el d—e b—e ]
Arguments and Values:
bytespec—a byte specifier .
integer—an integer .
byte, new-byte—a non-negative integer .
Description:
ldb extracts and returns the byte of integer specified by bytespec.
ldb returns an integer in which the bits with weights 2(s1) through 20 are the same as those in integer with weights 2(p+s1) through 2p, and all other bits zero; s is (byte-size bytespec) and p is (byte-position bytespec).
setf may be used with ldb to modify a byte within the integer that is stored in a given place. The order of evaluation, when an ldb form is supplied to setf, is exactly left-to-right. The e↵ect is to perform a dpb operation and then store the result back into the place.
Examples:
(ldb (byte 2 1) 10) *!* 1
(setq a (list 8)) *!* (8)
(setf (ldb (byte 2 1) (car a)) 1) *!* 1
a *!* (10)
See Also:
byte, byte-position, byte-size, dpb
Notes:
(logbitp j (ldb (byte s p) n))
⌘ (and (< j s) (logbitp (+ j p) n))
In general,
(ldb (byte 0 x) y) ! 0
for all valid values of x and y.
Historically, the name “ldb” comes from a DEC PDP-10 assembly language instruction meaning “load byte.”
Expanded Reference: ldb
Basic byte extraction
ldb (load byte) extracts a field of bits from an integer, returning them right-justified.
(ldb (byte 2 1) 10)
=> 1
(ldb (byte 4 0) #xFF)
=> 15
(ldb (byte 4 4) #xFF)
=> 15
(ldb (byte 8 0) #xABCD)
=> 205
Extracting individual bits
Use a byte of size 1 to extract a single bit.
(ldb (byte 1 0) 5)
=> 1
(ldb (byte 1 1) 5)
=> 0
(ldb (byte 1 2) 5)
=> 1
setf with ldb
ldb is a setf-able accessor. Using setf with ldb modifies a byte within a place.
(let ((a (list 8)))
(setf (ldb (byte 2 1) (car a)) 1)
a)
=> (10)
(let ((x 0))
(setf (ldb (byte 4 4) x) #xA)
x)
=> 160
Zero-width byte always returns zero
(ldb (byte 0 0) 12345)
=> 0
(ldb (byte 0 99) -1)
=> 0
Practical use: extracting fields from a packed integer
;; A date packed as: year (12 bits) | month (4 bits) | day (5 bits)
(let ((packed-date (logior (ash 2025 9) (ash 6 5) 15)))
(list (ldb (byte 12 9) packed-date) ; year
(ldb (byte 4 5) packed-date) ; month
(ldb (byte 5 0) packed-date))) ; day
=> (2025 6 15)
Relationship to dpb
ldb and dpb are inverse operations: ldb extracts what dpb deposits.
(let ((bs (byte 4 4)))
(ldb bs (dpb #xA bs 0)))
=> 10