国产探花免费观看_亚洲丰满少妇自慰呻吟_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 機器翻譯

下一篇:歸并排序

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 肇庆市| 墨脱县| 龙南县| 仙游县| 阳山县| 财经| 铁岭市| 华亭县| 新建县| 东平县| 华蓥市| 延吉市| 铜川市| 开鲁县| 德安县| 黑河市| 景洪市| 松滋市| 丰原市| 巴南区| 五河县| 镇宁| 绥宁县| 旬邑县| 同心县| 临湘市| 宁远县| 巴塘县| 普宁市| 嘉鱼县| 响水县| 灯塔市| 民和| 阳谷县| 清水县| 屏山县| 新龙县| 姚安县| 桂平市| 武平县| 高密市|