各种进制转换mark贴

之前遇到的一些问题..mark一下

 

package zhenghui.jvm.parse;

/**
 * Created by IntelliJ IDEA.
 * User: zhenghui
 * Date: 13-1-14
 * Time: 下午4:43
 * 表示无符号数.类似在jvm specs里规定的u1,u2,u4,u8
 */
public class Type {
    /**
     * 对应的16进制表示值
     */
    private String value;

    Type(String value) {
        this.value = value;
    }

    /**
     * 转换成十进制Integer
     *
     * @return
     */
    public int getDecimalInteger() {
        return Integer.parseInt(value, 16);
    }

    /**
     * 转换成十进制Float
     *
     * @return
     */
    public float getDecimalFloat(){
        return Float.intBitsToFloat(getDecimalInteger());
    }

    /**
     * 转换成十进制Long
     *
     * @return
     */
    public long getDecimalLong(){
        byte readBuffer[] = hexStringToByte(value);
        return (((long)readBuffer[0] << 56) +
                ((long)(readBuffer[1] & 255) << 48) +
                ((long)(readBuffer[2] & 255) << 40) +
                ((long)(readBuffer[3] & 255) << 32) +
                ((long)(readBuffer[4] & 255) << 24) +
                ((readBuffer[5] & 255) << 16) +
                ((readBuffer[6] & 255) <<  8) +
                ((readBuffer[7] & 255) <<  0));

//        return Long.parseLong(value,16);
    }

    /**
     * 转换成十进制Long
     *
     * @return
     */
    public double getDecimalDouble(){
        return Double.longBitsToDouble(getDecimalLong());
    }

    /**
     * 获取对应的16进制表示值
     *
     * @return
     */
    public String getValue() {
        return value;
    }

    private byte[] hexStringToByte(String hex) {
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }

    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }
}

 

 /**
     * load class 生成对应的16进制的字符串
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public String loadClass(String filePath) throws Exception {
        File file = new File(filePath);
        if(!file.exists()){
            return null;
        }
        System.out.println("filename:"+file.getName());
        FileInputStream fileInputStream = new FileInputStream(filePath);
        int i;
        StringBuilder sb = new StringBuilder();
        while ((i = fileInputStream.read()) != -1) {
            sb.append(String.format("%02X", i));
        }
        fileInputStream.close();
        return sb.toString();
    }

 

你可能感兴趣的:(进制转换)