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);
38 public Bit or(Bit other)
40 return fromTable(OR_TABLE, this, other);
44 public Bit xor(Bit other)
46 return fromTable(XOR_TABLE, this, other);
65 public Bit[] makeArray(int length)
67 Bit[] bits = new Bit[length];
68 Arrays.fill(bits, this);
72 public BitVector toVector()
74 return BitVector.of(this, 1);
77 public BitVector toVector(int length)
79 return BitVector.of(this, length);
83 public Bit join(Bit other)
85 return fromTable(JOIN_TABLE, this, other);
88 public static void join(Bit[] dst, Bit[] src)
90 for (int i = 0; i < dst.length; i++)
91 dst[i] = dst[i].join(src[i]);
95 public String toString()
100 public String getSymbol()
105 public static Bit lastBitOf(int value)
107 return values()[2 + (value & 1)];
110 public static Bit of(boolean binaryValue)
112 return binaryValue ? ONE : ZERO;
115 public static Bit parse(String s)
117 Bit bit = SYMBOL_MAP.get(s);
118 Objects.requireNonNull(bit, "No Bit found for symbol " + s);
122 public static Bit parse(String s, int symbolPosition)
124 return parse(s.substring(symbolPosition, symbolPosition + 1));
127 private static Bit fromTable(Bit[][] table, Bit a, Bit b)
129 return table[a.ordinal()][b.ordinal()];
132 static final Map<String, Bit> SYMBOL_MAP = Map.of(U.symbol, U, X.symbol, X, ZERO.symbol, ZERO, ONE.symbol, ONE, Z.symbol, Z);
135 private static final Bit[][] JOIN_TABLE =
138 { U, X, ZERO, X, ZERO },
139 { U, X, X, ONE, ONE },
140 { U, X, ZERO, ONE, Z } };
142 private static final Bit[][] AND_TABLE =
143 { { U, U, ZERO, U, U },
144 { U, X, ZERO, X, X },
145 { ZERO, ZERO, ZERO, ZERO, ZERO },
146 { U, X, ZERO, ONE, X },
147 { U, X, ZERO, X, X } };
149 private static final Bit[][] OR_TABLE =
150 { { U, U, U, ONE, U },
152 { U, X, ZERO, ONE, X },
153 { ONE, ONE, ONE, ONE, ONE },
154 { U, X, X, ONE, X } };
156 private static final Bit[][] XOR_TABLE =
159 { U, X, ZERO, ONE, X },
160 { U, X, ONE, ZERO, X },