Bitwise operations using binary representation of integers #
THIS FILE IS SYNCHRONIZED WITH MATHLIB4. Any changes to this file require a corresponding PR to mathlib4.
Definitions #
Bitwise "or" for pos_num
.
Bitwise "and" for pos_num
.
Bitwise "xor" for pos_num
.
a.test_bit n
is tt
iff the n
-th bit (starting from the LSB) in the binary representation
of a
is active. If the size of a
is less than n
, this evaluates to ff
.
Right-shift the binary representation of a pos_num
.
This is a nonzero (and "non minus one") version of snum
.
See the documentation of snum
for more details.
Instances for nzsnum
- nzsnum.has_sizeof_inst
- nzsnum.has_reflect
- snum.has_coe
- nzsnum.has_one
- nzsnum.inhabited
Alternative representation of integers using a sign bit at the end.
The convention on sign here is to have the argument to msb
denote
the sign of the MSB itself, with all higher bits set to the negation
of this sign. The result is interpreted in two's complement.
13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt))))
-13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff))))
As with num
, a special case must be added for zero, which has no msb,
but by two's complement symmetry there is a second special case for -1.
Here the bool
field indicates the sign of the number.
0 = ..0000000(base 2) = zero ff
-1 = ..1111111(base 2) = zero tt
Instances for snum
Equations
- snum.has_coe = {coe := snum.nz}
Equations
Equations
- snum.has_one = {one := snum.nz 1}
Equations
- nzsnum.inhabited = {default := 1}
Equations
- snum.inhabited = {default := 0}
The snum
representation uses a bit string, essentially a list of 0 (ff
) and 1 (tt
) bits,
and the negation of the MSB is sign-extended to all higher bits.
Add an inactive bit at the end of a nzsnum
. This mimics pos_num.bit0
.
Equations
Add an active bit at the end of a nzsnum
. This mimics pos_num.bit1
.
Equations
A dependent induction principle for nzsnum
, with base cases
0 : snum
and (-1) : snum
.
Equations
- nzsnum.drec' z s (b::p) = s b ↑p (nzsnum.drec' z s p)
- nzsnum.drec' z s (nzsnum.msb b) = _.mpr (s b (snum.zero (!b)) (z (!b)))
A dependent induction principle for snum
which avoids relying on nzsnum
.
Equations
- snum.drec' z s (snum.nz p) = nzsnum.drec' z s p
- snum.drec' z s (snum.zero b) = z b
snum.test_bit n a
is tt
iff the n
-th bit (starting from the LSB) of a
is active.
If the size of a
is less than n
, this evaluates to ff
.
Equations
- snum.test_bit (n + 1) p = snum.test_bit n p.tail
- snum.test_bit 0 p = p.head
Equations
- snum.has_neg = {neg := snum.neg}
snum.czadd a b n
is n + a - b
(where a
and b
should be read as either 0 or 1).
This is useful to implement the carry system in cadd
.
Equations
- snum.czadd bool.tt bool.tt p = p
- snum.czadd bool.tt bool.ff p = p.succ
- snum.czadd bool.ff bool.tt p = p.pred
- snum.czadd bool.ff bool.ff p = p
Equations
- snum.has_add = {add := snum.add}
Equations
- snum.has_sub = {sub := snum.sub}
Equations
- snum.has_mul = {mul := snum.mul}