Rev 218 | Blame | Compare with Previous | Last modification | View Log | RSS feed
/******************************************************************************** File: P2_EncDec.java* Author: Ira W. Snyder (devel@irasnyder.com)* License: GNU General Public License v2* Class: CS380 - Computer Networking** Assignment: Project #2* Date Last Modified: 2006-02-04** Purpose: Encode / Decode a number to / from 4B5B Encoding.*******************************************************************************/import java.io.*;import java.util.*;public class P2_EncDec{public static final String[][] encodingTable = {{ "0000", "11110" },{ "0001", "01001" },{ "0010", "10100" },{ "0011", "10101" },{ "0100", "01010" },{ "0101", "01011" },{ "0110", "01110" },{ "0111", "01111" },{ "1000", "10010" },{ "1001", "10011" },{ "1010", "10110" },{ "1011", "10111" },{ "1100", "11010" },{ "1101", "11011" },{ "1110", "11100" },{ "1111", "11101" }};/*** Method: convert4B()* Purpose: Convert a number from it's 4B representation to the* corresponding 5B representation.*/public static byte[] convert4B (byte[] _4BNum){String s = convertToString (_4BNum);int i = encodingTable.length - 1;for (; i >= 0; i--)if (encodingTable[i][0].equals(s))return convertToByteArray(encodingTable[i][1]);throw new IllegalArgumentException();}/*** Method: convert5B()* Purpose: Convert a number from it's 5B representation to the* corresponding 4B representation.*/public static byte[] convert5B (byte[] _5BNum){int i = encodingTable.length - 1;String s = convertToString (_5BNum);for (; i>=0; i--)if (encodingTable[i][1].equals(s))return convertToByteArray(encodingTable[i][0]);throw new IllegalArgumentException();}/*** Method: convertToByteArray()* Purpose: Convert a String to a byte[], useful for sending* over the network in a Datagram.*/public static byte[] convertToByteArray (String num){int i;byte[] ret = new byte[num.length()];byte temp;for (i=0; i<ret.length; i++){if (num.charAt(i) == '0')temp = 0;else if (num.charAt(i) == '1')temp = 1;elsethrow new IllegalArgumentException();ret[i] = temp;}return ret;}/*** Method: convertToString()* Purpose: Convert a byte[] to a String. This is really useful for* performing table lookups in the Encoder / Decoder.*/public static String convertToString (byte[] num){int i;String s = new String();for (i=0; i<num.length; i++)s = new String (s + num[i]);return s;}}