java資料格式轉換
阿新 • • 發佈:2018-12-31
/** * 字串轉換成十六進位制字串 * @param String str 待轉換的ASCII字串 * @return String 每個Byte之間空格分隔,如: [61 6C 6B] */ 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(); } /** * 十六進位制轉換字串 * @param String str Byte字串(Byte之間無分隔符 如:[616C6B]) * @return String 對應的字串 */ public static String hexStr2Str(String hexStr) { String str = "0123456789ABCDEF"; char[] hexs = hexStr.toCharArray(); byte[] bytes = new byte[hexStr.length() / 2]; int n; for (int i = 0; i < bytes.length; i++) { n = str.indexOf(hexs[2 * i]) * 16; n += str.indexOf(hexs[2 * i + 1]); bytes[i] = (byte) (n & 0xff); } return new String(bytes); } /** * bytes轉換成十六進位制字串 * @param byte[] b byte陣列 * @return String 每個Byte值之間空格分隔 */ public static String byte2HexStr(byte[] b) { String stmp=""; StringBuilder sb = new StringBuilder(""); for (int n=0;n<b.length;n++) { stmp = Integer.toHexString(b[n] & 0xFF); sb.append((stmp.length()==1)? "0"+stmp : stmp); sb.append(" "); } return sb.toString().toUpperCase().trim(); } /** * 十進位制轉化為十六進位制 */ public static String toHexStr(int data) { return Integer.toHexString(data); }
/** * 十六進位制轉化為十進位制 */
public static int toParseInt(String data) { return Integer.parseInt(data,16); }