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(int length)
92 return BitVector.of(this, length);
96 public Bit join(Bit other)
98 return fromTable(JOIN_TABLE, this, other);
101 public static void join(Bit[] dst, Bit[] src)
103 for (int i = 0; i < dst.length; i++)
104 dst[i] = dst[i].join(src[i]);
108 public String toString()
113 public String getSymbol()
118 public static Bit lastBitOf(int value)
120 return values()[2 + (value & 1)];
123 public static Bit of(boolean binaryValue)
125 return binaryValue ? ONE : ZERO;
128 public static Bit parse(String s)
130 Bit bit = SYMBOL_MAP.get(s);
131 Objects.requireNonNull(bit, "No Bit found for symbol " + s);
135 public static Bit parse(String s, int symbolPosition)
137 return parse(s.substring(symbolPosition, symbolPosition + 1));
140 private static Bit fromTable(Bit[][] table, Bit a, Bit b)
142 return table[a.ordinal()][b.ordinal()];
145 static final Map<String, Bit> SYMBOL_MAP = Map.of(U.symbol, U, X.symbol, X, ZERO.symbol, ZERO, ONE.symbol, ONE, Z.symbol, Z);
148 private static final Bit[][] JOIN_TABLE =
151 { U, X, ZERO, X, ZERO },
152 { U, X, X, ONE, ONE },
153 { U, X, ZERO, ONE, Z } };
155 private static final Bit[][] AND_TABLE =
156 { { U, U, ZERO, U, U },
157 { U, X, ZERO, X, X },
158 { ZERO, ZERO, ZERO, ZERO, ZERO },
159 { U, X, ZERO, ONE, X },
160 { U, X, ZERO, X, X } };
162 private static final Bit[][] OR_TABLE =
163 { { U, U, U, ONE, U },
165 { U, X, ZERO, ONE, X },
166 { ONE, ONE, ONE, ONE, ONE },
167 { U, X, X, ONE, X } };
169 private static final Bit[][] XOR_TABLE =
172 { U, X, ZERO, ONE, X },
173 { U, X, ONE, ZERO, X },