Bitwise Operations and Sets
Posted on January 1, 2013
Tags: algorithms
1 Basics
- Extract: First take \(n\) from singleton Set
- Encode: Use n as exponent in Decimal representation \(2^n\)
- Convert: Convert base, \(2^n :: \text{Decimal}\) to Binary representation
Set | Encoding | Binary | Python |
---|---|---|---|
\(\emptyset\) | \(0\) | \(00000\) | 0 |
\(\{0\}\) | \(2^0=1\) | \(00001\) | 0 |
\(\{1\}\) | \(2^1=2\) | \(00010\) | 0 |
\(\{2\}\) | \(2^2=4\) | \(00100\) | 0 |
\(\{3\}\) | \(2^3=8\) | \(01000\) | 0 |
\(\{4\}\) | \(2^4=16\) | \(10000\) | 0 |
\(\{0,1,2,3\}\) | \(2^4 - 1=15\) | \(01111\) | 0 |
\(\{3,4\}\) | \(2^3 + 2^4=24\) | \(11000\) | 0 |
\(Set \rightarrow Encoding\)
\(\{n\} \mapsto 2^n\)
\(\{0,1,2,..n-1\} \mapsto 2^n-1\)
Why do we take n from \(\{n\}\) and Encode it by turning it into the exponent instead of simply converting to another base?
2 bitwise shift
2.1 shift right
5 >> 3
\[ floor(\frac{5}{2^3})\]
2.2 shift left
5 << 2
\[ 5 \times 2^3 \]
3 Sets
#eval (bit1 3) + (bit0 4)
Bit :=
inductive | one : Bit
| zero : Bit
deriving Repr
-- class Addbit (T : Type) where
-- add : T -> T -> T
Bit
open
instance: Add Bit where
: Bit -> Bit -> Bit :=
add => match (x, y) with
λ x y | (one, one) => one
| (one, zero) => one
| (zero, one) => one
| (zero, zero) => zero
#eval one + one
instance: AndOp Bit where
and : Bit -> Bit -> Bit :=
=> match (x, y) with
λ x y | (one, one) => one
| (one, zero) => zero
| (zero, one) => zero
| (zero, zero) => zero
#eval one &&& one
#eval (. &&& one) <$> [zero,one]
-- #eval [(λ x => x &&& one),(λ x => x &&& one)] <*> [zero,one]
-- #eval [(λ x y => x + y),(λ x y => x * y)] <*> [1,2] <*> [3,4]
instance: Applicative List where
pure x := [x]
seq f x :=
match f with | [] => []
| f::fs => f <$> x ⟨⟩
#eval [(. + 1)] <*> [3,6]