Documentation

CslibFrontier.Foundations.Data.Nat.Bitwise.Carry

Bits of successors, predecessors and packed fields #

Incrementing a number flips bit q exactly when all lower bits are one, and decrementing a positive number flips it exactly when all lower bits are zero. A number packed from fields of fixed widths has, in each window of bits, the bits of the corresponding field.

Main results #

theorem Nat.testBit_sub_one_eq_xor {c : ℕ} (hc : 1 ≤ c) (q : ℕ) :
(c - 1).testBit q = (c.testBit q ^^ decide (c % 2 ^ q = 0))

Bit q of c - 1, for 1 ≤ c: bit q of c, flipped when the lower bits of c are zero.

theorem Nat.testBit_add_one_eq_xor (c q : ℕ) :
(c + 1).testBit q = (c.testBit q ^^ decide (c % 2 ^ q = 2 ^ q - 1))

Bit q of c + 1: bit q of c, flipped when the lower bits of c are all one.

theorem Nat.testBit_add_four_mul {tag : ℕ} (htag : tag < 4) (pay i : ℕ) :
(tag + 4 * pay).testBit i = if i < 2 then tag.testBit i else pay.testBit (i - 2)

The bits of a tag and a payload.

theorem Nat.testBit_add_two_pow_mul_add_two_pow_mul {s cb sl C Tm : ℕ} (hsl : sl < 2 ^ s) (hC : C < 2 ^ cb) (q : ℕ) :
(sl + 2 ^ s * (C + 2 ^ cb * Tm)).testBit q = if q < s then sl.testBit q else if q < s + cb then C.testBit (q - s) else Tm.testBit (q - s - cb)

The bits of three fields of widths s and cb and a high field.

theorem Nat.testBit_sub_two_pow {m a : ℕ} (h : m.testBit a = true) (c : ℕ) :
(m - 2 ^ a).testBit c = (m.testBit c && decide (c ≠ a))

Removing a set bit: the bits of m - 2 ^ a, when bit a of m is set, are those of m other than a.

theorem Nat.eq_two_pow_of_testBit {m a : ℕ} (h : ∀ (c : ℕ), m.testBit c = true ↔ c = a) :
m = 2 ^ a

A natural number whose only set bit is a is 2 ^ a.

theorem Nat.testBit_add_one_eq_ite_forall (c q : ℕ) :
(c + 1).testBit q = if ∀ i < q, c.testBit i = true then !c.testBit q else c.testBit q

Bit q of c + 1 flips iff all lower bits i < q of c are true.

theorem Nat.testBit_add_one_of_lowest {N j : ℕ} (hj : N.testBit j = false) (hlow : ∀ l < j, N.testBit l = true) (l : ℕ) :
(N + 1).testBit l = if l ≤ j then !N.testBit l else N.testBit l

Adding one to N complements the bits up to and including its lowest zero bit j.