字节、字符串、hex字符串 相互转换工具类

旧城等待, 2023-10-05 21:21 115阅读 0赞
  1. package com.lys.sec.common;
  2. import java.math.BigInteger;
  3. public class ByteHexUtil {
  4. /**
  5. * 整形转换成网络传输的字节流(字节数组)型数据
  6. *
  7. * @param num
  8. * 一个整型数据
  9. * @return 4个字节的自己数组
  10. */
  11. public static byte[] intToBytes(int num) {
  12. byte[] bytes = new byte[4];
  13. bytes[0] = (byte) (0xff & (num >> 0));
  14. bytes[1] = (byte) (0xff & (num >> 8));
  15. bytes[2] = (byte) (0xff & (num >> 16));
  16. bytes[3] = (byte) (0xff & (num >> 24));
  17. return bytes;
  18. }
  19. /**
  20. * 四个字节的字节数据转换成一个整形数据
  21. *
  22. * @param bytes
  23. * 4个字节的字节数组
  24. * @return 一个整型数据
  25. */
  26. public static int byteToInt(byte[] bytes) {
  27. int num = 0;
  28. int temp;
  29. temp = (0x000000ff & (bytes[0])) << 0;
  30. num = num | temp;
  31. temp = (0x000000ff & (bytes[1])) << 8;
  32. num = num | temp;
  33. temp = (0x000000ff & (bytes[2])) << 16;
  34. num = num | temp;
  35. temp = (0x000000ff & (bytes[3])) << 24;
  36. num = num | temp;
  37. return num;
  38. }
  39. /**
  40. * 长整形转换成网络传输的字节流(字节数组)型数据
  41. *
  42. * @param num
  43. * 一个长整型数据
  44. * @return 4个字节的自己数组
  45. */
  46. public static byte[] longToBytes(long num) {
  47. byte[] bytes = new byte[8];
  48. for (int i = 0; i < 8; i++) {
  49. bytes[i] = (byte) (0xff & (num >> (i * 8)));
  50. }
  51. return bytes;
  52. }
  53. /**
  54. * 大数字转换字节流(字节数组)型数据
  55. *
  56. * @param n
  57. * @return
  58. */
  59. public static byte[] byteConvert32Bytes(BigInteger n) {
  60. byte tmpd[] = (byte[]) null;
  61. if (n == null) {
  62. return null;
  63. }
  64. if (n.toByteArray().length == 33) {
  65. tmpd = new byte[32];
  66. System.arraycopy(n.toByteArray(), 1, tmpd, 0, 32);
  67. } else if (n.toByteArray().length == 32) {
  68. tmpd = n.toByteArray();
  69. } else {
  70. tmpd = new byte[32];
  71. for (int i = 0; i < 32 - n.toByteArray().length; i++) {
  72. tmpd[i] = 0;
  73. }
  74. System.arraycopy(n.toByteArray(), 0, tmpd, 32 - n.toByteArray().length, n.toByteArray().length);
  75. }
  76. return tmpd;
  77. }
  78. /**
  79. * 换字节流(字节数组)型数据转大数字
  80. *
  81. * @param b
  82. * @return
  83. */
  84. public static BigInteger byteConvertInteger(byte[] b) {
  85. if (b[0] < 0) {
  86. byte[] temp = new byte[b.length + 1];
  87. temp[0] = 0;
  88. System.arraycopy(b, 0, temp, 1, b.length);
  89. return new BigInteger(temp);
  90. }
  91. return new BigInteger(b);
  92. }
  93. /**
  94. * 根据字节数组获得值(十六进制数字)
  95. *
  96. * @param bytes
  97. * @return
  98. */
  99. public static String getHexString(byte[] bytes) {
  100. return getHexString(bytes, true);
  101. }
  102. /**
  103. * 根据字节数组获得值(十六进制数字)
  104. *
  105. * @param bytes
  106. * @param upperCase
  107. * @return
  108. */
  109. public static String getHexString(byte[] bytes, boolean upperCase) {
  110. String ret = "";
  111. for (int i = 0; i < bytes.length; i++) {
  112. ret += Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1);
  113. }
  114. return upperCase ? ret.toUpperCase() : ret;
  115. }
  116. /**
  117. * 打印十六进制字符串
  118. *
  119. * @param bytes
  120. */
  121. public static void printHexString(byte[] bytes) {
  122. for (int i = 0; i < bytes.length; i++) {
  123. String hex = Integer.toHexString(bytes[i] & 0xFF);
  124. if (hex.length() == 1) {
  125. hex = '0' + hex;
  126. }
  127. System.out.print("0x" + hex.toUpperCase() + ",");
  128. }
  129. System.out.println("");
  130. }
  131. /**
  132. * Convert hex string to byte[]
  133. *
  134. * @param hexString
  135. * the hex string
  136. * @return byte[]
  137. */
  138. public static byte[] hexStringToBytes(String hexString) {
  139. if (hexString == null || hexString.equals("")) {
  140. return null;
  141. }
  142. hexString = hexString.toUpperCase();
  143. int length = hexString.length() / 2;
  144. char[] hexChars = hexString.toCharArray();
  145. byte[] d = new byte[length];
  146. for (int i = 0; i < length; i++) {
  147. int pos = i * 2;
  148. d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
  149. }
  150. return d;
  151. }
  152. /**
  153. * Convert char to byte
  154. *
  155. * @param c
  156. * char
  157. * @return byte
  158. */
  159. public static byte charToByte(char c) {
  160. return (byte) "0123456789ABCDEF".indexOf(c);
  161. }
  162. /**
  163. * 用于建立十六进制字符的输出的小写字符数组
  164. */
  165. private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
  166. 'e', 'f' };
  167. /**
  168. * 用于建立十六进制字符的输出的大写字符数组
  169. */
  170. private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
  171. 'E', 'F' };
  172. /**
  173. * 将字节数组转换为十六进制字符数组
  174. *
  175. * @param data
  176. * byte[]
  177. * @return 十六进制char[]
  178. */
  179. public static char[] encodeHex(byte[] data) {
  180. return encodeHex(data, true);
  181. }
  182. /**
  183. * 将字节数组转换为十六进制字符数组
  184. *
  185. * @param data
  186. * byte[]
  187. * @param toLowerCase
  188. * <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
  189. * @return 十六进制char[]
  190. */
  191. public static char[] encodeHex(byte[] data, boolean toLowerCase) {
  192. return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
  193. }
  194. /**
  195. * 将字节数组转换为十六进制字符数组
  196. *
  197. * @param data
  198. * byte[]
  199. * @param toDigits
  200. * 用于控制输出的char[]
  201. * @return 十六进制char[]
  202. */
  203. protected static char[] encodeHex(byte[] data, char[] toDigits) {
  204. int l = data.length;
  205. char[] out = new char[l << 1];
  206. // two characters form the hex value.
  207. for (int i = 0, j = 0; i < l; i++) {
  208. out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
  209. out[j++] = toDigits[0x0F & data[i]];
  210. }
  211. return out;
  212. }
  213. /**
  214. * 将字节数组转换为十六进制字符串
  215. *
  216. * @param data
  217. * byte[]
  218. * @return 十六进制String
  219. */
  220. public static String encodeHexString(byte[] data) {
  221. return encodeHexString(data, true);
  222. }
  223. /**
  224. * 将字节数组转换为十六进制字符串
  225. *
  226. * @param data
  227. * byte[]
  228. * @param toLowerCase
  229. * <code>true</code> 传换成小写格式 , <code>false</code> 传换成大写格式
  230. * @return 十六进制String
  231. */
  232. public static String encodeHexString(byte[] data, boolean toLowerCase) {
  233. return encodeHexString(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
  234. }
  235. /**
  236. * 将字节数组转换为十六进制字符串
  237. *
  238. * @param data
  239. * byte[]
  240. * @param toDigits
  241. * 用于控制输出的char[]
  242. * @return 十六进制String
  243. */
  244. protected static String encodeHexString(byte[] data, char[] toDigits) {
  245. return new String(encodeHex(data, toDigits));
  246. }
  247. /**
  248. * 将十六进制字符数组转换为字节数组
  249. *
  250. * @param data
  251. * 十六进制char[]
  252. * @return byte[]
  253. * @throws RuntimeException
  254. * 如果源十六进制字符数组是一个奇怪的长度,将抛出运行时异常
  255. */
  256. public static byte[] decodeHex(char[] data) {
  257. int len = data.length;
  258. if ((len & 0x01) != 0) {
  259. throw new RuntimeException("Odd number of characters.");
  260. }
  261. byte[] out = new byte[len >> 1];
  262. // two characters form the hex value.
  263. for (int i = 0, j = 0; j < len; i++) {
  264. int f = toDigit(data[j], j) << 4;
  265. j++;
  266. f = f | toDigit(data[j], j);
  267. j++;
  268. out[i] = (byte) (f & 0xFF);
  269. }
  270. return out;
  271. }
  272. /**
  273. * 将十六进制字符转换成一个整数
  274. *
  275. * @param ch
  276. * 十六进制char
  277. * @param index
  278. * 十六进制字符在字符数组中的位置
  279. * @return 一个整数
  280. * @throws RuntimeException
  281. * 当ch不是一个合法的十六进制字符时,抛出运行时异常
  282. */
  283. protected static int toDigit(char ch, int index) {
  284. int digit = Character.digit(ch, 16);
  285. if (digit == -1) {
  286. throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
  287. }
  288. return digit;
  289. }
  290. /**
  291. * 数字字符串转ASCII码字符串
  292. *
  293. * @param String
  294. * 字符串
  295. * @return ASCII字符串
  296. */
  297. public static String StringToAsciiString(String content) {
  298. String result = "";
  299. int max = content.length();
  300. for (int i = 0; i < max; i++) {
  301. char c = content.charAt(i);
  302. String b = Integer.toHexString(c);
  303. result = result + b;
  304. }
  305. return result;
  306. }
  307. /**
  308. * 十六进制转字符串
  309. *
  310. * @param hexString
  311. * 十六进制字符串
  312. * @param encodeType
  313. * 编码类型4:Unicode,2:普通编码
  314. * @return 字符串
  315. */
  316. public static String hexStringToString(String hexString, int encodeType) {
  317. String result = "";
  318. int max = hexString.length() / encodeType;
  319. for (int i = 0; i < max; i++) {
  320. char c = (char) hexStringToAlgorism(hexString.substring(i * encodeType, (i + 1) * encodeType));
  321. result += c;
  322. }
  323. return result;
  324. }
  325. /**
  326. * 十六进制字符串装十进制
  327. *
  328. * @param hex
  329. * 十六进制字符串
  330. * @return 十进制数值
  331. */
  332. public static int hexStringToAlgorism(String hex) {
  333. hex = hex.toUpperCase();
  334. int max = hex.length();
  335. int result = 0;
  336. for (int i = max; i > 0; i--) {
  337. char c = hex.charAt(i - 1);
  338. int algorism = 0;
  339. if (c >= '0' && c <= '9') {
  340. algorism = c - '0';
  341. } else {
  342. algorism = c - 55;
  343. }
  344. result += Math.pow(16, max - i) * algorism;
  345. }
  346. return result;
  347. }
  348. /**
  349. * 十六转二进制
  350. *
  351. * @param hex
  352. * 十六进制字符串
  353. * @return 二进制字符串
  354. */
  355. public static String hexStringToBinary(String hex) {
  356. hex = hex.toUpperCase();
  357. String result = "";
  358. int max = hex.length();
  359. for (int i = 0; i < max; i++) {
  360. char c = hex.charAt(i);
  361. switch (c) {
  362. case '0':
  363. result += "0000";
  364. break;
  365. case '1':
  366. result += "0001";
  367. break;
  368. case '2':
  369. result += "0010";
  370. break;
  371. case '3':
  372. result += "0011";
  373. break;
  374. case '4':
  375. result += "0100";
  376. break;
  377. case '5':
  378. result += "0101";
  379. break;
  380. case '6':
  381. result += "0110";
  382. break;
  383. case '7':
  384. result += "0111";
  385. break;
  386. case '8':
  387. result += "1000";
  388. break;
  389. case '9':
  390. result += "1001";
  391. break;
  392. case 'A':
  393. result += "1010";
  394. break;
  395. case 'B':
  396. result += "1011";
  397. break;
  398. case 'C':
  399. result += "1100";
  400. break;
  401. case 'D':
  402. result += "1101";
  403. break;
  404. case 'E':
  405. result += "1110";
  406. break;
  407. case 'F':
  408. result += "1111";
  409. break;
  410. }
  411. }
  412. return result;
  413. }
  414. /**
  415. * ASCII码字符串转数字字符串
  416. *
  417. * @param String
  418. * ASCII字符串
  419. * @return 字符串
  420. */
  421. public static String AsciiStringToString(String content) {
  422. String result = "";
  423. int length = content.length() / 2;
  424. for (int i = 0; i < length; i++) {
  425. String c = content.substring(i * 2, i * 2 + 2);
  426. int a = hexStringToAlgorism(c);
  427. char b = (char) a;
  428. String d = String.valueOf(b);
  429. result += d;
  430. }
  431. return result;
  432. }
  433. /**
  434. * 将十进制转换为指定长度的十六进制字符串
  435. *
  436. * @param algorism
  437. * int 十进制数字
  438. * @param maxLength
  439. * int 转换后的十六进制字符串长度
  440. * @return String 转换后的十六进制字符串
  441. */
  442. public static String algorismToHexString(int algorism, int maxLength) {
  443. String result = "";
  444. result = Integer.toHexString(algorism);
  445. if (result.length() % 2 == 1) {
  446. result = "0" + result;
  447. }
  448. return patchHexString(result.toUpperCase(), maxLength);
  449. }
  450. /**
  451. * 字节数组转为普通字符串(ASCII对应的字符)
  452. *
  453. * @param bytearray
  454. * byte[]
  455. * @return String
  456. */
  457. public static String byteToString(byte[] bytearray) {
  458. String result = "";
  459. char temp;
  460. int length = bytearray.length;
  461. for (int i = 0; i < length; i++) {
  462. temp = (char) bytearray[i];
  463. result += temp;
  464. }
  465. return result;
  466. }
  467. /**
  468. * 二进制字符串转十进制
  469. *
  470. * @param binary
  471. * 二进制字符串
  472. * @return 十进制数值
  473. */
  474. public static int binaryToAlgorism(String binary) {
  475. int max = binary.length();
  476. int result = 0;
  477. for (int i = max; i > 0; i--) {
  478. char c = binary.charAt(i - 1);
  479. int algorism = c - '0';
  480. result += Math.pow(2, max - i) * algorism;
  481. }
  482. return result;
  483. }
  484. /**
  485. * 十进制转换为十六进制字符串
  486. *
  487. * @param algorism
  488. * int 十进制的数字
  489. * @return String 对应的十六进制字符串
  490. */
  491. public static String algorismToHEXString(int algorism) {
  492. String result = "";
  493. result = Integer.toHexString(algorism);
  494. if (result.length() % 2 == 1) {
  495. result = "0" + result;
  496. }
  497. result = result.toUpperCase();
  498. return result;
  499. }
  500. /**
  501. * HEX字符串前补0,主要用于长度位数不足。
  502. *
  503. * @param str
  504. * String 需要补充长度的十六进制字符串
  505. * @param maxLength
  506. * int 补充后十六进制字符串的长度
  507. * @return 补充结果
  508. */
  509. static public String patchHexString(String str, int maxLength) {
  510. String temp = "";
  511. for (int i = 0; i < maxLength - str.length(); i++) {
  512. temp = "0" + temp;
  513. }
  514. str = (temp + str).substring(0, maxLength);
  515. return str;
  516. }
  517. /**
  518. * 将一个字符串转换为int
  519. *
  520. * @param s
  521. * String 要转换的字符串
  522. * @param defaultInt
  523. * int 如果出现异常,默认返回的数字
  524. * @param radix
  525. * int 要转换的字符串是什么进制的,如16 8 10.
  526. * @return int 转换后的数字
  527. */
  528. public static int parseToInt(String s, int defaultInt, int radix) {
  529. int i = 0;
  530. try {
  531. i = Integer.parseInt(s, radix);
  532. } catch (NumberFormatException ex) {
  533. i = defaultInt;
  534. }
  535. return i;
  536. }
  537. /**
  538. * 将一个十进制形式的数字字符串转换为int
  539. *
  540. * @param s
  541. * String 要转换的字符串
  542. * @param defaultInt
  543. * int 如果出现异常,默认返回的数字
  544. * @return int 转换后的数字
  545. */
  546. public static int parseToInt(String s, int defaultInt) {
  547. int i = 0;
  548. try {
  549. i = Integer.parseInt(s);
  550. } catch (NumberFormatException ex) {
  551. i = defaultInt;
  552. }
  553. return i;
  554. }
  555. /**
  556. * 十六进制串转化为byte数组
  557. *
  558. * @return the array of byte
  559. */
  560. public static byte[] hexToByte(String hex) throws IllegalArgumentException {
  561. if (hex.length() % 2 != 0) {
  562. throw new IllegalArgumentException();
  563. }
  564. char[] arr = hex.toCharArray();
  565. byte[] b = new byte[hex.length() / 2];
  566. for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
  567. String swap = "" + arr[i++] + arr[i];
  568. int byteint = Integer.parseInt(swap, 16) & 0xFF;
  569. b[j] = new Integer(byteint).byteValue();
  570. }
  571. return b;
  572. }
  573. /**
  574. * 字节数组转换为十六进制字符串
  575. *
  576. * @param b
  577. * byte[] 需要转换的字节数组
  578. * @return String 十六进制字符串
  579. */
  580. public static String byteToHex(byte b[]) {
  581. if (b == null) {
  582. throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
  583. }
  584. String hs = "";
  585. String stmp = "";
  586. for (int n = 0; n < b.length; n++) {
  587. stmp = Integer.toHexString(b[n] & 0xff);
  588. if (stmp.length() == 1) {
  589. hs = hs + "0" + stmp;
  590. } else {
  591. hs = hs + stmp;
  592. }
  593. }
  594. return hs.toUpperCase();
  595. }
  596. public static byte[] subByte(byte[] input, int startIndex, int length) {
  597. byte[] bt = new byte[length];
  598. for (int i = 0; i < length; i++) {
  599. bt[i] = input[i + startIndex];
  600. }
  601. return bt;
  602. }
  603. }

发表评论

表情:
评论列表 (有 0 条评论,115人围观)

还没有评论,来说两句吧...

相关阅读