16進位制,byte,byte陣列之間裝換
阿新 • • 發佈:2019-01-03
package com.rmt.updata; import java.util.Locale; public class Hex { /** * 字串轉換成十六進位制字串 * @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(Locale.ENGLISH).trim(); } /** * bytes字串轉換為Byte值 * @param String * src Byte字串,每個Byte之間沒有分隔符 * @return byte[] */ public static byte[] hexStr2Bytes(String src) { int m = 0, n = 0; int l = src.length() / 2; System.out.println(l); byte[] ret = new byte[l]; for (int i = 0; i < l; i++) { m = i * 2 + 1; n = m + 1; ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n)); } return ret; } /** * String的字串轉換成unicode的String * @param String * strText 全形字串 * @return String 每個unicode之間無分隔符 * @throws Exception */ public static String strToUnicode(String strText) throws Exception { char c; StringBuilder str = new StringBuilder(); int intAsc; String strHex; for (int i = 0; i < strText.length(); i++) { c = strText.charAt(i); intAsc = (int) c; strHex = Integer.toHexString(intAsc); if (intAsc > 128) str.append("\\u" + strHex); else str.append("\\u00" + strHex); // 低位在前面補00 } return str.toString(); } /** * unicode的String轉換成String的字串 * @param String * hex 16進位制值字串 (一個unicode為2byte) * @return String 全形字串 */ public static String unicodeToString(String hex) { int t = hex.length() / 6; StringBuilder str = new StringBuilder(); for (int i = 0; i < t; i++) { String s = hex.substring(i * 6, (i + 1) * 6); String s1 = s.substring(2, 4) + "00"; // 高位需要補上00再轉 String s2 = s.substring(4); // 低位直接轉 int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16); // 將16進位制的string轉為int char[] chars = Character.toChars(n); // 將int轉換為字元 str.append(new String(chars)); } return str.toString(); } }