/** * This class is used for unsigned binary numbers of 8 bits length * * @author Mr J * @version 20040221 */ class BinaryTextField extends java.awt.TextField { // Constructors (as for TextField) public BinaryTextField() { super(); } public BinaryTextField(int columns) { super(columns); } public BinaryTextField(String text) { super(text); } public BinaryTextField(String text, int columns) { super(text, columns); } /** * This method returns a valid binary String of 8 bits or passes up an exception * @return java.lang.String * @throws BinaryTextFieldException */ public String binaryValue() throws BinaryTextFieldException { // Use the TextField built-in method for getting the text String s = super.getText(); if ( isBinary() ) // method to test if is valid binary string { return s; } else { return null; // return a null value on error } } /** * This method tests the binary number to see if it is a valid * 8-bit binary unsigned integer * @return true if the byte is valid * @throws BinaryTextFieldException */ public boolean isBinary() throws BinaryTextFieldException { boolean ok = true; String s = super.getText(); if ( s.length() != 8 ) // byte must have 8 bits { // throw an exception with a custom error message ok = false; throw new BinaryTextFieldException("Bad byte length"); } else { int pos = 0; char c; while ( (pos < 8) && (ok) ) { c = s.charAt(pos); if ( (c != '0') && (c != '1') ) // each bit must be a 1 or a 0 { ok = false; throw new BinaryTextFieldException("Bad digit " + c + " at " + (++pos)); } pos++; } return (ok); } } /** * This method converts a valid, unsigned binary String of 8 bits to an integer * @return int * @throws BinaryTextFieldException if value in field is invalid */ public int convert() throws BinaryTextFieldException { int sum = 0; int weight = 1; String s = binaryValue(); // start at the LSB (right end of String) // if the digit is a 1, add it in for (int pos = 7; pos >= 0; pos--) { if ( s.charAt(pos) == '1' ) { sum += weight; } weight *= 2; // next digit up is worth twice as much as this one } return(sum); } }