国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Java中byte數組和16進制字符串互相轉換

2019-11-14 12:56:24
字體:
來源:轉載
供稿:網友

首先,byte數組轉成16進制字符串:

/** * byte數組轉成字符串 * * @param bytes 數組 * @param isCaptial 使用大寫還是小寫表示 * @return 轉換后的字符串 */public static String bytesToHexStr(byte[] bytes, boolean isCaptial) { if (null == bytes || bytes.length <= 0) { return null; } StringBuilder s = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { if (isCaptial) { //02表示使用2位16進制字符表示當前的byte數據,X或者x表示16進制字符串 s.append(String.format("%02X", bytes[i])); } else { s.append(String.format("%02x", bytes[i])); } } return s.toString(); }

然后,將16進制字符串轉成byte數組:

public static byte[] hexStrToBytes(String hex) { if (null == hex || hex.equals("")) { return null; } int strLength = hex.length();//獲取16進制字符串長度 int length = strLength / 2; //獲取字節長度 char[] hexChars;//用來存放字符串轉換成的字符數組 if (length * 2 < strLength) { // strLength is odd, add '0' length += 1; hexChars = ("0" + hex).toCharArray(); } else { hexChars = hex.toCharArray(); } byte[] bytes = new byte[length];//用來存放最終組成的數組 for (int i = 0; i < length; i++) { int pos = i * 2; //組成1字節的數據。因為是需要兩個字符組成一個字節的數據,這就需要第一個字符向左移4位。 bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); } return bytes; }public static byte charToByte(char c) { byte result = (byte) "0123456789abcdef".indexOf(c); if (result == -1) { return (byte) "0123456789ABCDEF".indexOf(c); } else { return result; } }
上一篇:P1540 機器翻譯

下一篇:歸并排序

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 息烽县| 兴业县| 萨迦县| 昌平区| 揭西县| 漯河市| 远安县| 漯河市| 平乡县| 布拖县| 池州市| 葵青区| 永丰县| 太仓市| 开阳县| 玛纳斯县| 宁乡县| 沙田区| 永年县| 上林县| 遵义县| 洛南县| 北京市| 徐水县| 响水县| 新密市| 开鲁县| 板桥市| 龙州县| 方城县| 阿拉善左旗| 吴堡县| 大新县| 综艺| 潜江市| 平定县| 贺兰县| 漾濞| 凉山| 榆社县| 天峨县|