1 package net.mograsim.machine.isa;
3 import java.math.BigInteger;
5 import net.mograsim.logic.core.types.Bit;
6 import net.mograsim.logic.core.types.BitVector;
7 import net.mograsim.logic.core.types.BitVector.BitVectorMutator;
8 import net.mograsim.machine.isa.types.AsmNumberFormatException;
10 public class AsmIntegerOperand implements AsmOperand
12 private final int size;
14 public AsmIntegerOperand(int size)
26 public BitVector parse(String s) throws AsmNumberFormatException
28 String cleaned = s.replace("_", "").toLowerCase();
29 int len = cleaned.length();
33 if (cleaned.startsWith("0x"))
34 res = new BigInteger(cleaned.substring(2), 16);
35 else if (cleaned.endsWith("h"))
36 res = new BigInteger(cleaned.substring(0, len - 1), 16);
37 else if (cleaned.startsWith("0b"))
38 res = new BigInteger(cleaned.substring(2), 2);
39 else if (cleaned.endsWith("b"))
40 res = new BigInteger(cleaned.substring(2), 2);
41 else if (cleaned.endsWith("q"))
42 res = new BigInteger(cleaned.substring(0, len - 1), 8);
44 res = new BigInteger(cleaned);
46 catch (NumberFormatException e)
48 throw new AsmNumberFormatException(e, "Error parsing %s: no valid integer format", s);
50 return bigIntToBitVector(res);
53 BitVector bigIntToBitVector(BigInteger bi) throws AsmNumberFormatException
55 int bitLength = bi.bitLength() - (bi.signum() - 1) / 2;
57 throw new AsmNumberFormatException("Error parsing %s: bit count %d exceeds size %d", bi, bitLength, size);
58 BitVectorMutator bvm = BitVectorMutator.ofWidth(size);
59 for (int i = 0; i < size; i++)
60 bvm.setLSBit(i, Bit.of(bi.testBit(i)));
61 return bvm.toBitVector();
64 public static void main(String[] args) throws AsmNumberFormatException
66 AsmIntegerOperand aio = new AsmIntegerOperand(4);
67 System.out.println(aio.parse("0"));
68 System.out.println(aio.parse("1"));
69 System.out.println(aio.parse("2"));
70 System.out.println(aio.parse("3"));
71 System.out.println(aio.parse("4"));
72 System.out.println(aio.parse("5"));
73 System.out.println(aio.parse("6"));
74 System.out.println(aio.parse("7"));
75 System.out.println(aio.parse("8"));
76 System.out.println(aio.parse("9"));
77 System.out.println(aio.parse("10"));
78 System.out.println(aio.parse("11"));
79 System.out.println(aio.parse("12"));
80 System.out.println(aio.parse("13"));
81 System.out.println(aio.parse("14"));
82 System.out.println(aio.parse("15"));
83 // System.out.println(aio.parse("16"));
84 System.out.println(aio.parse("-0"));
85 System.out.println(aio.parse("-1"));
86 System.out.println(aio.parse("-2"));
87 System.out.println(aio.parse("-3"));
88 System.out.println(aio.parse("-4"));
89 System.out.println(aio.parse("-5"));
90 System.out.println(aio.parse("-6"));
91 System.out.println(aio.parse("-7"));
92 System.out.println(aio.parse("-8"));
93 // System.out.println(aio.parse("-9"));