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

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Java中byte數(shù)組和16進(jìn)制字符串互相轉(zhuǎn)換

2019-11-14 12:55:24
字體:
供稿:網(wǎng)友

首先,byte數(shù)組轉(zhuǎn)成16進(jìn)制字符串:

/** * byte數(shù)組轉(zhuǎn)成字符串 * * @param bytes 數(shù)組 * @param isCaptial 使用大寫還是小寫表示 * @return 轉(zhuǎn)換后的字符串 */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進(jìn)制字符表示當(dāng)前的byte數(shù)據(jù),X或者x表示16進(jìn)制字符串 s.append(String.format("%02X", bytes[i])); } else { s.append(String.format("%02x", bytes[i])); } } return s.toString(); }

然后,將16進(jìn)制字符串轉(zhuǎn)成byte數(shù)組:

public static byte[] hexStrToBytes(String hex) { if (null == hex || hex.equals("")) { return null; } int strLength = hex.length();//獲取16進(jìn)制字符串長(zhǎng)度 int length = strLength / 2; //獲取字節(jié)長(zhǎng)度 char[] hexChars;//用來存放字符串轉(zhuǎn)換成的字符數(shù)組 if (length * 2 < strLength) { // strLength is odd, add '0' length += 1; hexChars = ("0" + hex).toCharArray(); } else { hexChars = hex.toCharArray(); } byte[] bytes = new byte[length];//用來存放最終組成的數(shù)組 for (int i = 0; i < length; i++) { int pos = i * 2; //組成1字節(jié)的數(shù)據(jù)。因?yàn)槭切枰獌蓚€(gè)字符組成一個(gè)字節(jié)的數(shù)據(jù),這就需要第一個(gè)字符向左移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; } }
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 沁源县| 锦州市| 吉水县| 桐乡市| 进贤县| 新化县| 舒兰市| 观塘区| 大冶市| 定结县| 绥中县| 洮南市| 南昌市| 根河市| 抚顺县| 肥乡县| 昭觉县| 常山县| 泾源县| 巫山县| 金平| 天台县| 宿松县| 高唐县| 长汀县| 商河县| 灵璧县| 宝山区| 肇东市| 汤原县| 迭部县| 武隆县| 阳朔县| 遂溪县| 扎鲁特旗| 璧山县| 沾益县| 襄垣县| 太原市| 宝应县| 隆尧县|