1 package net.mograsim.logic.core.types;
3 import java.util.Arrays;
5 import java.util.Objects;
8 * stdlogic according to IEEE 1164
10 public enum Bit implements StrictLogicType<Bit>
12 U("U"), X("X"), ZERO("0"), ONE("1"), Z("Z");
14 private final String symbol;
16 private Bit(String symbol)
22 * Returns if the Bit is binary, this is only true for <code>ZERO</code> and <code>ONE</code>.
24 * @return true if and only if <code>this == ONE || this == ZERO</code>
26 public boolean isBinary()
28 return this == ONE || this == ZERO;
32 public Bit and(Bit other)
34 return fromTable(AND_TABLE, this, other);
37 public static void and(Bit[] dst, Bit[] src)
39 for (int i = 0; i < dst.length; i++)
40 dst[i] = dst[i].and(src[i]);
44 public Bit or(Bit other)
46 return fromTable(OR_TABLE, this, other);
49 public static void or(Bit[] dst, Bit[] src)
51 for (int i = 0; i < dst.length; i++)
52 dst[i] = dst[i].or(src[i]);
56 public Bit xor(Bit other)
58 return fromTable(XOR_TABLE, this, other);
61 public static void xor(Bit[] dst, Bit[] src)
63 for (int i = 0; i < dst.length; i++)
64 dst[i] = dst[i].xor(src[i]);
83 public Bit[] makeArray(int length)
85 Bit[] bits = new Bit[length];
86 Arrays.fill(bits, this);
90 public BitVector toVector()
92 return BitVector.of(this, 1);
95 public BitVector toVector(int length)
97 return BitVector.of(this, length);
101 public Bit join(Bit other)
103 return fromTable(JOIN_TABLE, this, other);
106 public static void join(Bit[] dst, Bit[] src)
108 for (int i = 0; i < dst.length; i++)
109 dst[i] = dst[i].join(src[i]);
113 public String toString()
118 public String getSymbol()
123 public static Bit lastBitOf(int value)
125 return values()[2 + (value & 1)];
128 public static Bit of(boolean binaryValue)
130 return binaryValue ? ONE : ZERO;
133 public static Bit parse(String s)
135 Bit bit = SYMBOL_MAP.get(s);
136 Objects.requireNonNull(bit, "No Bit found for symbol " + s);
140 public static Bit parse(String s, int symbolPosition)
142 return parse(s.substring(symbolPosition, symbolPosition + 1));
145 private static Bit fromTable(Bit[][] table, Bit a, Bit b)
147 return table[a.ordinal()][b.ordinal()];
150 static final Map<String, Bit> SYMBOL_MAP = Map.of(U.symbol, U, X.symbol, X, ZERO.symbol, ZERO, ONE.symbol, ONE, Z.symbol, Z);
153 private static final Bit[][] JOIN_TABLE =
156 { U, X, ZERO, X, ZERO },
157 { U, X, X, ONE, ONE },
158 { U, X, ZERO, ONE, Z } };
160 private static final Bit[][] AND_TABLE =
161 { { U, U, ZERO, U, U },
162 { U, X, ZERO, X, X },
163 { ZERO, ZERO, ZERO, ZERO, ZERO },
164 { U, X, ZERO, ONE, X },
165 { U, X, ZERO, X, X } };
167 private static final Bit[][] OR_TABLE =
168 { { U, U, U, ONE, U },
170 { U, X, ZERO, ONE, X },
171 { ONE, ONE, ONE, ONE, ONE },
172 { U, X, X, ONE, X } };
174 private static final Bit[][] XOR_TABLE =
177 { U, X, ZERO, ONE, X },
178 { U, X, ONE, ZERO, X },