备份一下老帖子拉,:) --------------------------------------------------------------------------- 嘿嘿,索性把hex/bin正反转换都写出来,没准以后还能抄自己的程序呢,hia hia |
//-----------------------------------------------//
// HEX to BIN & BIN to HEX Class //
// FreeDebug (c) 2003-12-11 //
//-----------------------------------------------//
import java.util.*;
class HexBinExchange {
// change a num from HEX to BIN
public static String hex2Bin( String sHex ) {
String sTmp = "";
StringBuffer sbResult = new StringBuffer();
for (int i=0; i<sHex.length(); i++) {
sTmp = sHex.substring(i,i+1);
for (int j=0; j<16; j++) {
if (sTmp.compareToIgnoreCase(sCode[j][0])==0) {
sbResult.append(sCode[j][1]);
break;
}
}
}
return sbResult.toString();
}
// chage a num from BIN to HEX
public static String bin2Hex( String sBin ) {
// Count how many zero will fill in the front of sBin
int iFillZero = sBin.length() % 4;
if ( iFillZero != 0 ) iFillZero = 4 - iFillZero;
// Fill zero in the front of sBin
StringBuffer sbTmp = new StringBuffer();
for (int i=0; i<iFillZero; i++) sbTmp.append("0");
sBin = sbTmp.append( sBin ).toString();
// Okey, just like hex2Bin fuction
String sTmp = "";
StringBuffer sbResult = new StringBuffer();
for (int i=0; i<sBin.length(); i+=4) {
sTmp = sBin.substring(i,i+4);
for (int j=0; j<16; j++) {
if (sTmp.compareToIgnoreCase(sCode[j][1])==0) {
sbResult.append(sCode[j][0]);
break;
}
}
}
return sbResult.toString();
}
// A code table for exchange
private static String[][] sCode = {
{"0","0000"},
{"1","0001"},
{"2","0010"},
{"3","0011"},
{"4","0100"},
{"5","0101"},
{"6","0110"},
{"7","0111"},
{"8","1000"},
{"9","1001"},
{"A","1010"},
{"B","1011"},
{"C","1100"},
{"D","1101"},
{"E","1110"},
{"F","1111"} };
}
public class HexBinExchangeClass{
public static void main(String[] args) {
System.out.println( HexBinExchange.hex2Bin("70ABC12D") );
System.out.println( HexBinExchange.bin2Hex("1110000101010111100000100101101") );
}
}
///:~