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

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

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

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

首先,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; } }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 甘肃省| 永登县| 涞源县| 乌恰县| 安龙县| 巨野县| 新昌县| 黄骅市| 泾源县| 于都县| 赤水市| 澎湖县| 安图县| 江口县| 靖州| 浙江省| 衡山县| 长寿区| 新闻| 普兰店市| 来凤县| 南丹县| 台中县| 汤阴县| 三亚市| 金川县| 怀集县| 无棣县| 高邑县| 阳山县| 汾西县| 佛山市| 北京市| 贺州市| 河池市| 惠东县| 平顺县| 本溪| 岳池县| 嵊泗县| 淳化县|