java 工具類-進制的轉換

// 16進制轉換爲車牌
public static String hexStringToString(String s) {
    if (s == null || s.equals("")) {
        return null;
    }
    s = s.replace(" ", "");
    byte[] baKeyword = new byte[s.length() / 2];
    for (int i = 0; i < baKeyword.length; i++) {
        try {
            baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    try {
        s = new String(baKeyword, "UTF-8");
        new String();
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return s;
}
/**
 * 字符串轉換成爲16進制(無需Unicode編碼)
 * @param str
 * @return
 */
public static String str2HexStr(String str) {
    char[] chars = "0123456789ABCDEF".toCharArray();
    StringBuilder sb = new StringBuilder("");
    byte[] bs = str.getBytes();
    int bit;
    for (int i = 0; i < bs.length; i++) {
        bit = (bs[i] & 0x0f0) >> 4;
        sb.append(chars[bit]);
        bit = bs[i] & 0x0f;
        sb.append(chars[bit]);
        // sb.append(' ');
    }
    return sb.toString().trim();
}

// 16進制轉換爲10進制

public static int hexToInt(String hexs) {
    BigInteger bigint = new BigInteger(hexs, 16);
    int numb = bigint.intValue();
    return numb;
}

 

//16進制轉換爲 時間

public static String strToBJDate(String strDate) {
    int aa= hexToInt(strDate);
    String date = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date(new Long((long)aa) * 1000));
    Log.e("aa", "strToBJDate: " + date);
    return date;

}

// 16進制轉換爲 GB2312

public static String stringToGb2312(String string) {
    byte[] bytes = new byte[string.length() / 2];
    for (int i = 0; i < bytes.length; i++) {
        byte high = Byte.parseByte(string.substring(i * 2, i * 2 + 1), 16);
        byte low = Byte.parseByte(string.substring(i * 2 + 1, i * 2 + 2), 16);
        bytes[i] = (byte) (high << 4 | low);
    }
    String result = null;
    try {
        result = new String(bytes, "GB2312");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return result;
}

 

業餘記錄

//    String a = "京";
//            try {
//                byte[] b = a.getBytes("GB2312");
//                System.out.println(bytesToHexFun1(b));
//
//            } catch (UnsupportedEncodingException e) {
//                e.printStackTrace();
//            }

 

 

 

 

 

使用方式

@Test
public void testPlateNum() {

    //桂D89117
    String palteNum = hexStringToString("E6A182443839313137");
    System.out.println(palteNum);

    String plate = str2HexStr("桂D89117");
    System.out.println(plate);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章