手工换算 HEX to BIN & BIN to HEX

备份一下老帖子拉,:)
---------------------------------------------------------------------------

嘿嘿,索性把hex/bin正反转换都写出来,没准以后还能抄自己的程序呢,hia hia
//: HexBinExchangeClass.java

//-----------------------------------------------//
//        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") );
    }
}

///:~
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值