package com.imdroid.secapi.utils;

public class HexUtil {
    static public String Byte2HexString(byte value){
        String sv = "";
        byte bv = (byte) ((value >> 4)&0x0F);
        if(bv<10) sv+=bv;
        else sv+=(char) ('A'+bv-10);

        bv = (byte) (value & 0x0F);
        if(bv<10) sv+=bv;
        else sv+=(char) ('A'+bv-10);

        return sv;
    }

    static public String Short2HexString(short value){
        String sv = "";
        sv += Byte2HexString((byte) (value>>8));
        sv += Byte2HexString((byte) (value));
        return sv;
    }

    static public String Int2HexString(int value){
        String sv = "";
        sv += Byte2HexString((byte) (value>>24));
        sv += Byte2HexString((byte) (value>>16));
        sv += Byte2HexString((byte) (value>>8));
        sv += Byte2HexString((byte) (value));
        return sv;
    }

    static public String String2HexString(String value){
        byte[] data = value.getBytes();
        String sv = "";
        for(int i=0; i< data.length; i++) sv += Byte2HexString(data[i]);
        return sv;
    }

    static public String HexString2String(String value){
        String sv ="";
        int pos=0;
        int trans=0;
        short bv = 0;
        while(pos<value.length()){
            char ch = value.charAt(pos);
            if(ch<='9' && ch>='0'){
                bv = (short) (bv*16 + ch - '0');
                trans++;
            }
            else if(ch<='F' && ch>='A'){
                bv = (short) (bv*16 + ch - 'A' + 10);
                trans++;
            }
            else if(ch<='f' && ch>='a'){
                bv = (short) (bv*16 + ch - 'a' + 10);
                trans++;
            }
            if(trans==2) {
                sv += (char) bv;
                bv = 0;
                trans = 0;
            }
            pos++;
        }
        return sv;
    }

}
