字符串和byte[]的转换
Posted cipherlab
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串和byte[]的转换相关的知识,希望对你有一定的参考价值。
1 public static String bytesToHexString(byte[] src){ 2 StringBuilder stringBuilder = new StringBuilder(""); 3 if (src == null || src.length <= 0) { 4 return null; 5 } 6 for (int i = 0; i < src.length; i++) { 7 int v = src[i] & 0xFF; 8 String hv = Integer.toHexString(v).toUpperCase(); 9 if (hv.length() < 2) { 10 stringBuilder.append(0); 11 } 12 stringBuilder.append(hv); 13 } 14 return stringBuilder.toString(); 15 } 16 //这个是为了转15693的数据专用的,略去第一个字符,接下来中间每5个字符取后面4个字符,然后将其转为字符串 17 //为了存储用 18 public static String bytesToHexString1(byte[] src){ 19 StringBuilder stringBuilder = new StringBuilder(""); 20 if (src == null || src.length <= 0) { 21 return null; 22 } 23 for (int i = 2; i < src.length; i++) { 24 if(((i-1) % 5 == 0) && (i > 2)) 25 continue; 26 int v = src[i] & 0xFF; 27 String hv = Integer.toHexString(v).toUpperCase(); 28 if (hv.length() < 2) { 29 stringBuilder.append(0); 30 } 31 stringBuilder.append(hv); 32 } 33 return stringBuilder.toString(); 34 } 35 //这个是为了转15693的数据专用的,略去第一个字符,接下来中间每5个字符取后面4个字符,然后将其转为字符串 36 //为了显示用 37 public static String bytesToHexString2(byte[] src){ 38 StringBuilder stringBuilder = new StringBuilder(""); 39 if (src == null || src.length <= 0) { 40 return null; 41 } 42 for (int i = 2; i < src.length; i++) { 43 if(((i-1) % 5 == 0) && (i > 2)) 44 continue; 45 int v = src[i] & 0xFF; 46 String hv = Integer.toHexString(v).toUpperCase(); 47 if (hv.length() < 2) { 48 stringBuilder.append(0); 49 } 50 stringBuilder.append(hv + " "); 51 } 52 return stringBuilder.toString(); 53 } 54 55 /** 56 * Convert hex string to byte[] 57 * @param hexString the hex string 58 * @return byte[] 59 */ 60 public static byte[] hexStringToBytes(String hexString) { 61 if (hexString == null || hexString.equals("")) { 62 return null; 63 } 64 hexString = hexString.toUpperCase(); 65 int length = hexString.length() / 2; 66 char[] hexChars = hexString.toCharArray(); 67 byte[] d = new byte[length]; 68 for (int i = 0; i < length; i++) { 69 int pos = i * 2; 70 d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); 71 } 72 return d; 73 } 74 /** 75 * Convert char to byte 76 * @param c char 77 * @return byte 78 */ 79 public static byte charToByte(char c) { 80 return (byte) "0123456789ABCDEF".indexOf(c); 81 }
以上是关于字符串和byte[]的转换的主要内容,如果未能解决你的问题,请参考以下文章