improved int formatter

This commit is contained in:
hneemann 2017-12-16 10:45:52 +01:00
parent a488b6cc40
commit ce9d2e6211
2 changed files with 59 additions and 2 deletions

View File

@ -43,13 +43,41 @@ public enum IntFormat {
case dec:
return Long.toString(inValue.getValue());
case hex:
return Long.toHexString(inValue.getMaskedValue()).toUpperCase();
return toHex(inValue);
case bin:
return Long.toBinaryString(inValue.getMaskedValue());
return toBin(inValue);
case ascii:
return "" + (char) inValue.getValue();
default:
return inValue.getValueString();
}
}
private static String toHex(Value inValue) {
final int bits = inValue.getBits();
final int numChars = (bits - 1) / 4 + 1;
StringBuilder sb = new StringBuilder(numChars);
final long value = inValue.getValue();
for (int i = numChars - 1; i >= 0; i--) {
int c = (int) ((value >> (i * 4)) & 0xf);
sb.append("0123456789ABCDEF".charAt(c));
}
return sb.toString();
}
private static String toBin(Value inValue) {
final int bits = inValue.getBits();
StringBuilder sb = new StringBuilder(bits);
final long value = inValue.getValue();
long mask = 1L << (bits - 1);
for (int i = 0; i < bits; i++) {
if ((value & mask) != 0)
sb.append('1');
else
sb.append('0');
mask >>= 1;
}
return sb.toString();
}
}

View File

@ -0,0 +1,29 @@
package de.neemann.digital.core.io;
import de.neemann.digital.core.Value;
import junit.framework.TestCase;
public class IntFormatTest extends TestCase {
public void testHex() throws Exception {
assertEquals("1", IntFormat.hex.format(new Value(1, 1)));
assertEquals("1", IntFormat.hex.format(new Value(1, 2)));
assertEquals("1", IntFormat.hex.format(new Value(1, 3)));
assertEquals("1", IntFormat.hex.format(new Value(1, 4)));
assertEquals("F", IntFormat.hex.format(new Value(-1, 4)));
assertEquals("01", IntFormat.hex.format(new Value(1, 5)));
assertEquals("FF", IntFormat.hex.format(new Value(-1, 5)));
assertEquals("FFF", IntFormat.hex.format(new Value(-1, 12)));
assertEquals("FFFF", IntFormat.hex.format(new Value(-1, 13)));
assertEquals("FFFF", IntFormat.hex.format(new Value(-1, 14)));
assertEquals("FFFF", IntFormat.hex.format(new Value(-1, 15)));
assertEquals("FFFF", IntFormat.hex.format(new Value(-1, 16)));
}
public void testBin() throws Exception {
assertEquals("1", IntFormat.bin.format(new Value(1, 1)));
assertEquals("01", IntFormat.bin.format(new Value(1, 2)));
assertEquals("001", IntFormat.bin.format(new Value(1, 3)));
assertEquals("111", IntFormat.bin.format(new Value(-1, 3)));
}
}