TBCD编码最直观的人看解析的方法:把单字节的低四位和高四位互换,字节之间顺序别变。直接就好了,F就是空,什么都没有。 比如:
TBCD编码:0x31 0x55 0x40 0x20 0x79 0xF9 解码后原始:13 5504 02 97 9
以下是编码、解码代码 // package tbcd; /**
* This sample code demonstrates how a character string can be convered to * a TBCD (Telephony Binary Coded Decimal) string and vice versa. */
public class TBCDUtil {
private static String cTBCDSymbolString = \
private static char[] cTBCDSymbols = cTBCDSymbolString.toCharArray();
public static void main(String[] args) {
if (args.length == 0) return;
byte[] tbcd = parseTBCD(args[0]);
System.out.println(\System.out.println(\ }
/* * This method converts a TBCD string to a character string. */
public static java.lang.StringtoTBCD (byte[] tbcd) {
int size = (tbcd == null ? 0 : tbcd.length);
StringBuffer buffer = new StringBuffer(2*size); for (inti=0; i int n2 = (octet >> 4) & 0xF; int n1 = octet & 0xF; if (n1 == 15) { throw new NumberFormatException(\ } buffer.append(cTBCDSymbols[n1]); if (n2 == 15) { if (i != size-1) throw new NumberFormatException(\ } else buffer.append(cTBCDSymbols[n2]); } returnbuffer.toString(); } /* * This method converts a character string to a TBCD string. */ public static byte[] parseTBCD (java.lang.Stringtbcd) { int length = (tbcd == null ? 0:tbcd.length()); int size = (length + 1)/2; byte[] buffer = new byte[size]; for (inti=0, i1=0, i2=1; i char c = tbcd.charAt(i1); int n2 = getTBCDNibble(c, i1); int octet = 0; int n1 = 15; if (i2 < length) { c = tbcd.charAt(i2); n1 = getTBCDNibble(c, i2); } octet = (n1 << 4) + n2; buffer[i] = (byte)(octet & 0xFF); } return buffer; } private static intgetTBCDNibble(char c, int i1) { int n = Character.digit(c, 10); if (n < 0 || n > 9) { switch (c) { case '*': n = 10; break; case '#': n = 11; break; case 'a': n = 12; break; case 'b': n = 13; break; case 'c': n = 14; break; default: throw new NumberFormatException(\ + \ } } return n; } /* Hex chars */ private static final byte[] HEX_CHAR = new byte[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /* * Helper function that dumps an array of bytes in the hexadecimal format. */ public static final String dumpBytes( byte[] buffer ) { if ( buffer == null ) { return \ } StringBuffersb = new StringBuffer(); for ( inti = 0; i sb.append( \( char ) ( HEX_CHAR[buffer[i] & 0x000F] ) ).append( \ } returnsb.toString(); } }