【Java】字节数组转换工具类

  1 import org.apache.commons.lang.ArrayUtils;
  2 
  3 import java.nio.charset.Charset;
  4 
  5 /**
  6  * 字节数组转换工具类
  7  */
  8 public class BytesUtils {
  9 
 10     public static final String GBK = "GBK";
 11     public static final String UTF8 = "utf-8";
 12     public static final char[] ascii = "0123456789ABCDEF".toCharArray();
 13     private static char[] HEX_VOCABLE = { '0', '1', '2', '3', '4', '5', '6',
 14             '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
 15 
 16     /**
 17      * 将short整型数值转换为字节数组
 18      * 
 19      * @param data
 20      * @return
 21      */
 22     public static byte[] getBytes(short data) {
 23         byte[] bytes = new byte[2];
 24         bytes[0] = (byte) ((data & 0xff00) >> 8);
 25         bytes[1] = (byte) (data & 0xff);
 26         return bytes;
 27     }
 28 
 29     /**
 30      * 将字符转换为字节数组
 31      * 
 32      * @param data
 33      * @return
 34      */
 35     public static byte[] getBytes(char data) {
 36         byte[] bytes = new byte[2];
 37         bytes[0] = (byte) (data >> 8);
 38         bytes[1] = (byte) (data);
 39         return bytes;
 40     }
 41 
 42     /**
 43      * 将布尔值转换为字节数组
 44      * 
 45      * @param data
 46      * @return
 47      */
 48     public static byte[] getBytes(boolean data) {
 49         byte[] bytes = new byte[1];
 50         bytes[0] = (byte) (data ? 1 : 0);
 51         return bytes;
 52     }
 53 
 54     /**
 55      * 将整型数值转换为字节数组
 56      * 
 57      * @param data
 58      * @return
 59      */
 60     public static byte[] getBytes(int data) {
 61         byte[] bytes = new byte[4];
 62         bytes[0] = (byte) ((data & 0xff000000) >> 24);
 63         bytes[1] = (byte) ((data & 0xff0000) >> 16);
 64         bytes[2] = (byte) ((data & 0xff00) >> 8);
 65         bytes[3] = (byte) (data & 0xff);
 66         return bytes;
 67     }
 68 
 69     /**
 70      * 将long整型数值转换为字节数组
 71      * 
 72      * @param data
 73      * @return
 74      */
 75     public static byte[] getBytes(long data) {
 76         byte[] bytes = new byte[8];
 77         bytes[0] = (byte) ((data >> 56) & 0xff);
 78         bytes[1] = (byte) ((data >> 48) & 0xff);
 79         bytes[2] = (byte) ((data >> 40) & 0xff);
 80         bytes[3] = (byte) ((data >> 32) & 0xff);
 81         bytes[4] = (byte) ((data >> 24) & 0xff);
 82         bytes[5] = (byte) ((data >> 16) & 0xff);
 83         bytes[6] = (byte) ((data >> 8) & 0xff);
 84         bytes[7] = (byte) (data & 0xff);
 85         return bytes;
 86     }
 87 
 88     /**
 89      * 将float型数值转换为字节数组
 90      * 
 91      * @param data
 92      * @return
 93      */
 94     public static byte[] getBytes(float data) {
 95         int intBits = Float.floatToIntBits(data);
 96         return getBytes(intBits);
 97     }
 98 
 99     /**
100      * 将double型数值转换为字节数组
101      * 
102      * @param data
103      * @return
104      */
105     public static byte[] getBytes(double data) {
106         long intBits = Double.doubleToLongBits(data);
107         return getBytes(intBits);
108     }
109 
110     /**
111      * 将字符串按照charsetName编码格式的字节数组
112      * 
113      * @param data
114      *            字符串
115      * @param charsetName
116      *            编码格式
117      * @return
118      */
119     public static byte[] getBytes(String data, String charsetName) {
120         Charset charset = Charset.forName(charsetName);
121         return data.getBytes(charset);
122     }
123 
124     /**
125      * 将字符串按照GBK编码格式的字节数组
126      * 
127      * @param data
128      * @return
129      */
130     public static byte[] getBytes(String data) {
131         return getBytes(data, GBK);
132     }
133 
134     /**
135      * 将字节数组第0字节转换为布尔值
136      * 
137      * @param bytes
138      * @return
139      */
140     public static boolean getBoolean(byte[] bytes) {
141         return bytes[0] == 1;
142     }
143 
144     /**
145      * 将字节数组的第index字节转换为布尔值
146      * 
147      * @param bytes
148      * @param index
149      * @return
150      */
151     public static boolean getBoolean(byte[] bytes, int index) {
152         return bytes[index] == 1;
153     }
154 
155     /**
156      * 将字节数组前2字节转换为short整型数值
157      * 
158      * @param bytes
159      * @return
160      */
161     public static short getShort(byte[] bytes) {
162         return (short) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1]));
163     }
164 
165     /**
166      * 将字节数组从startIndex开始的2个字节转换为short整型数值
167      * 
168      * @param bytes
169      * @param startIndex
170      * @return
171      */
172     public static short getShort(byte[] bytes, int startIndex) {
173         return (short) ((0xff00 & (bytes[startIndex] << 8)) | (0xff & bytes[startIndex + 1]));
174     }
175 
176     /**
177      * 将字节数组前2字节转换为字符
178      * 
179      * @param bytes
180      * @return
181      */
182     public static char getChar(byte[] bytes) {
183         return (char) ((0xff00 & (bytes[0] << 8)) | (0xff & bytes[1]));
184     }
185 
186     /**
187      * 将字节数组从startIndex开始的2个字节转换为字符
188      * 
189      * @param bytes
190      * @param startIndex
191      * @return
192      */
193     public static char getChar(byte[] bytes, int startIndex) {
194         return (char) ((0xff00 & (bytes[startIndex] << 8)) | (0xff & bytes[startIndex + 1]));
195     }
196 
197     /**
198      * 将字节数组前4字节转换为整型数值
199      * 
200      * @param bytes
201      * @return
202      */
203     public static int getInt(byte[] bytes) {
204         return (0xff000000 & (bytes[0] << 24) | (0xff0000 & (bytes[1] << 16))
205                 | (0xff00 & (bytes[2] << 8)) | (0xff & bytes[3]));
206     }
207 
208     /**
209      * 将字节数组从startIndex开始的4个字节转换为整型数值
210      * 
211      * @param bytes
212      * @param startIndex
213      * @return
214      */
215     public static int getInt(byte[] bytes, int startIndex) {
216         return (0xff000000 & (bytes[startIndex] << 24)
217                 | (0xff0000 & (bytes[startIndex + 1] << 16))
218                 | (0xff00 & (bytes[startIndex + 2] << 8)) | (0xff & bytes[startIndex + 3]));
219     }
220 
221     /**
222      * 将字节数组前8字节转换为long整型数值
223      * 
224      * @param bytes
225      * @return
226      */
227     public static long getLong(byte[] bytes) {
228         return (0xff00000000000000L & ((long) bytes[0] << 56)
229                 | (0xff000000000000L & ((long) bytes[1] << 48))
230                 | (0xff0000000000L & ((long) bytes[2] << 40))
231                 | (0xff00000000L & ((long) bytes[3] << 32))
232                 | (0xff000000L & ((long) bytes[4] << 24))
233                 | (0xff0000L & ((long) bytes[5] << 16))
234                 | (0xff00L & ((long) bytes[6] << 8)) | (0xffL & (long) bytes[7]));
235     }
236 
237     /**
238      * 将字节数组从startIndex开始的8个字节转换为long整型数值
239      * 
240      * @param bytes
241      * @param startIndex
242      * @return
243      */
244     public static long getLong(byte[] bytes, int startIndex) {
245         return (0xff00000000000000L & ((long) bytes[startIndex] << 56)
246                 | (0xff000000000000L & ((long) bytes[startIndex + 1] << 48))
247                 | (0xff0000000000L & ((long) bytes[startIndex + 2] << 40))
248                 | (0xff00000000L & ((long) bytes[startIndex + 3] << 32))
249                 | (0xff000000L & ((long) bytes[startIndex + 4] << 24))
250                 | (0xff0000L & ((long) bytes[startIndex + 5] << 16))
251                 | (0xff00L & ((long) bytes[startIndex + 6] << 8)) | (0xffL & (long) bytes[startIndex + 7]));
252     }
253 
254     /**
255      * 将字节数组前4字节转换为float型数值
256      * 
257      * @param bytes
258      * @return
259      */
260     public static float getFloat(byte[] bytes) {
261         return Float.intBitsToFloat(getInt(bytes));
262     }
263 
264     /**
265      * 将字节数组从startIndex开始的4个字节转换为float型数值
266      * 
267      * @param bytes
268      * @param startIndex
269      * @return
270      */
271     public static float getFloat(byte[] bytes, int startIndex) {
272         byte[] result = new byte[4];
273         System.arraycopy(bytes, startIndex, result, 0, 4);
274         return Float.intBitsToFloat(getInt(result));
275     }
276 
277     /**
278      * 将字节数组前8字节转换为double型数值
279      * 
280      * @param bytes
281      * @return
282      */
283     public static double getDouble(byte[] bytes) {
284         long l = getLong(bytes);
285         return Double.longBitsToDouble(l);
286     }
287 
288     /**
289      * 将字节数组从startIndex开始的8个字节转换为double型数值
290      * 
291      * @param bytes
292      * @param startIndex
293      * @return
294      */
295     public static double getDouble(byte[] bytes, int startIndex) {
296         byte[] result = new byte[8];
297         System.arraycopy(bytes, startIndex, result, 0, 8);
298         long l = getLong(result);
299         return Double.longBitsToDouble(l);
300     }
301 
302     /**
303      * 将charsetName编码格式的字节数组转换为字符串
304      * 
305      * @param bytes
306      * @param charsetName
307      * @return
308      */
309     public static String getString(byte[] bytes, String charsetName) {
310         return new String(bytes, Charset.forName(charsetName));
311     }
312 
313     /**
314      * 将GBK编码格式的字节数组转换为字符串
315      * 
316      * @param bytes
317      * @return
318      */
319     public static String getString(byte[] bytes) {
320         return getString(bytes, GBK);
321     }
322 
323     /**
324      * 将16进制字符串转换为字节数组
325      * 
326      * @param hex
327      * @return
328      */
329     public static byte[] hexStringToBytes(String hex) {
330         if (hex == null || "".equals(hex)) {
331             return null;
332         }
333         int len = hex.length() / 2;
334         byte[] result = new byte[len];
335         char[] chArr = hex.toCharArray();
336         for (int i = 0; i < len; i++) {
337             int pos = i * 2;
338             result[i] = (byte) (toByte(chArr[pos]) << 4 | toByte(chArr[pos + 1]));
339         }
340         return result;
341     }
342     
343     /**
344      * 将16进制字符串转换为字节数组
345      * 
346      * @param hex
347      * @return
348      */
349     public static byte[] hexToBytes(String hex) {
350         if (hex.length() % 2 != 0)
351             throw new IllegalArgumentException(
352                     "input string should be any multiple of 2!");
353         hex.toUpperCase();
354 
355         byte[] byteBuffer = new byte[hex.length() / 2];
356 
357         byte padding = 0x00;
358         boolean paddingTurning = false;
359         for (int i = 0; i < hex.length(); i++) {
360             if (paddingTurning) {
361                 char c = hex.charAt(i);
362                 int index = indexOf(hex, c);
363                 padding = (byte) ((padding << 4) | index);
364                 byteBuffer[i / 2] = padding;
365                 padding = 0x00;
366                 paddingTurning = false;
367             } else {
368                 char c = hex.charAt(i);
369                 int index = indexOf(hex, c);
370                 padding = (byte) (padding | index);
371                 paddingTurning = true;
372             }
373 
374         }
375         return byteBuffer;
376     }
377 
378     private static int indexOf(String input, char c) {
379         int index = ArrayUtils.indexOf(HEX_VOCABLE, c);
380 
381         if (index < 0) {
382             throw new IllegalArgumentException("err input:" + input);
383         }
384         return index;
385 
386     }
387 
388     /**
389      * 将BCD编码的字节数组转换为字符串
390      * 
391      * @param bcds
392      * @return
393      */
394     public static String bcdToString(byte[] bcds) {
395         if (bcds == null || bcds.length == 0) {
396             return null;
397         }
398         byte[] temp = new byte[2 * bcds.length];
399         for (int i = 0; i < bcds.length; i++) {
400             temp[i * 2] = (byte) ((bcds[i] >> 4) & 0x0f);
401             temp[i * 2 + 1] = (byte) (bcds[i] & 0x0f);
402         }
403         StringBuffer res = new StringBuffer();
404         for (int i = 0; i < temp.length; i++) {
405             res.append(ascii[temp[i]]);
406         }
407         return res.toString();
408     }
409 
410     /**
411      * 字节转整形
412      * @param value
413      * @return
414      */
415     public static int bcdToInt(byte value){
416         return ((value>>4) * 10) + (value&0x0F);
417     }
418     
419     /**
420      * 字节数组转16进制字符串
421      * @param bs
422      * @return
423      */
424     public static String bytesToHex(byte[] bs) {
425         StringBuilder sb = new StringBuilder();
426         for (byte b : bs) {
427             int high = (b >> 4) & 0x0f;
428             int low = b & 0x0f;
429             sb.append(HEX_VOCABLE[high]);
430             sb.append(HEX_VOCABLE[low]);
431         }
432         return sb.toString();
433     }
434     
435     /**
436      * 字节数组取前len个字节转16进制字符串
437      * @param bs
438      * @param len
439      * @return
440      */
441     public static String bytesToHex(byte[] bs, int len) {
442         StringBuilder sb = new StringBuilder();
443         for (int i=0; i<len; i++ ) {
444             byte b = bs[i];
445             int high = (b >> 4) & 0x0f;
446             int low = b & 0x0f;
447             sb.append(HEX_VOCABLE[high]);
448             sb.append(HEX_VOCABLE[low]);
449         }
450         return sb.toString();
451     }
452     /**
453      * 字节数组偏移offset长度之后的取len个字节转16进制字符串
454      * @param bs
455      * @param offset
456      * @param len
457      * @return
458      */
459     public static String bytesToHex(byte[] bs, int offset, int len) {
460         StringBuilder sb = new StringBuilder();
461         for (int i=0; i<len; i++ ) {
462             byte b = bs[offset + i];
463             int high = (b >> 4) & 0x0f;
464             int low = b & 0x0f;
465             sb.append(HEX_VOCABLE[high]);
466             sb.append(HEX_VOCABLE[low]);
467         }
468         return sb.toString();
469     }
470     /**
471      * 字节数组转16进制字符串
472      * @param bs
473      * @return
474      */
475     public static String byteToHex(byte b) {
476         StringBuilder sb = new StringBuilder();
477             int high = (b >> 4) & 0x0f;
478             int low = b & 0x0f;
479             sb.append(HEX_VOCABLE[high]);
480             sb.append(HEX_VOCABLE[low]);
481         return sb.toString();
482     }
483     /**
484      * 将字节数组取反
485      * 
486      * @param src
487      * @return
488      */
489     public static String negate(byte[] src) {
490         if (src == null || src.length == 0) {
491             return null;
492         }
493         byte[] temp = new byte[2 * src.length];
494         for (int i = 0; i < src.length; i++) {
495             byte tmp = (byte) (0xFF ^ src[i]);
496             temp[i * 2] = (byte) ((tmp >> 4) & 0x0f);
497             temp[i * 2 + 1] = (byte) (tmp & 0x0f);
498         }
499         StringBuffer res = new StringBuffer();
500         for (int i = 0; i < temp.length; i++) {
501             res.append(ascii[temp[i]]);
502         }
503         return res.toString();
504     }
505 
506     /**
507      * 比较字节数组是否相同
508      * 
509      * @param a
510      * @param b
511      * @return
512      */
513     public static boolean compareBytes(byte[] a, byte[] b) {
514         if (a == null || a.length == 0 || b == null || b.length == 0
515                 || a.length != b.length) {
516             return false;
517         }
518         if (a.length == b.length) {
519             for (int i = 0; i < a.length; i++) {
520                 if (a[i] != b[i]) {
521                     return false;
522                 }
523             }
524         } else {
525             return false;
526         }
527         return true;
528     }
529     /**
530      * 只比对指定长度byte
531      * @param a
532      * @param b
533      * @param len
534      * @return
535      */
536     public static boolean compareBytes(byte[] a, byte[] b, int len) {
537         if (a == null || a.length == 0 || b == null || b.length == 0
538                 || a.length < len || b.length < len) {
539             return false;
540         }
541         for (int i = 0; i < len; i++) {
542             if (a[i] != b[i]) {
543                 return false;
544             }
545         }
546         return true;
547     }
548 
549     /**
550      * 将字节数组转换为二进制字符串
551      * 
552      * @param items
553      * @return
554      */
555     public static String bytesToBinaryString(byte[] items) {
556         if (items == null || items.length == 0) {
557             return null;
558         }
559         StringBuffer buf = new StringBuffer();
560         for (byte item : items) {
561             buf.append(byteToBinaryString(item));
562         }
563         return buf.toString();
564     }
565 
566     /**
567      * 将字节转换为二进制字符串
568      * 
569      * @param items
570      * @return
571      */
572     public static String byteToBinaryString(byte item) {
573         byte a = item;
574         StringBuffer buf = new StringBuffer();
575         for (int i = 0; i < 8; i++) {
576             buf.insert(0, a % 2);
577             a = (byte) (a >> 1);
578         }
579         return buf.toString();
580     }
581 
582     /**
583      * 对数组a,b进行异或运算
584      * 
585      * @param a
586      * @param b
587      * @return
588      */
589     public static byte[] xor(byte[] a, byte[] b) {
590         if (a == null || a.length == 0 || b == null || b.length == 0
591                 || a.length != b.length) {
592             return null;
593         }
594         byte[] result = new byte[a.length];
595         for (int i = 0; i < a.length; i++) {
596             result[i] = (byte) (a[i] ^ b[i]);
597         }
598         return result;
599     }
600 
601     /**
602      * 对数组a,b进行异或运算 运算长度len
603      * @param a
604      * @param b
605      * @param len
606      * @return
607      */
608     public static byte[] xor(byte[] a, byte[] b, int len) {
609         if (a == null || a.length == 0 || b == null || b.length == 0) {
610             return null;
611         }
612         if (a.length < len || b.length < len){
613             return null;
614         }
615         byte[] result = new byte[len];
616         for (int i = 0; i < len; i++) {
617             result[i] = (byte) (a[i] ^ b[i]);
618         }
619         return result;
620     }
621     /**
622      * 将short整型数值转换为字节数组
623      * 
624      * @param num
625      * @return
626      */
627     public static byte[] shortToBytes(int num) {
628         byte[] temp = new byte[2];
629         for (int i = 0; i < 2; i++) {
630             temp[i] = (byte) ((num >>> (8 - i * 8)) & 0xFF);
631         }
632         return temp;
633     }
634 
635     /**
636      * 将字节数组转为整型
637      * 
638      * @param num
639      * @return
640      */
641     public static int bytesToShort(byte[] arr) {
642         int mask = 0xFF;
643         int temp = 0;
644         int result = 0;
645         for (int i = 0; i < 2; i++) {
646             result <<= 8;
647             temp = arr[i] & mask;
648             result |= temp;
649         }
650         return result;
651     }
652 
653     /**
654      * 将整型数值转换为指定长度的字节数组
655      * 
656      * @param num
657      * @return
658      */
659     public static byte[] intToBytes(int num) {
660         byte[] temp = new byte[4];
661         for (int i = 0; i < 4; i++) {
662             temp[i] = (byte) ((num >>> (24 - i * 8)) & 0xFF);
663         }
664         return temp;
665     }
666 
667     /**
668      * 将整型数值转换为指定长度的字节数组
669      * 
670      * @param src
671      * @param len
672      * @return
673      */
674     public static byte[] intToBytes(int src, int len) {
675         if (len < 1 || len > 4) {
676             return null;
677         }
678         byte[] temp = new byte[len];
679         for (int i = 0; i < len; i++) {
680             temp[len - 1 - i] = (byte) ((src >>> (8 * i)) & 0xFF);
681         }
682         return temp;
683     }
684 
685     /**
686      * 将字节数组转换为整型数值
687      * 
688      * @param arr
689      * @return
690      */
691     public static int bytesToInt(byte[] arr) {
692         int mask = 0xFF;
693         int temp = 0;
694         int result = 0;
695         for (int i = 0; i < 4; i++) {
696             result <<= 8;
697             temp = arr[i] & mask;
698             result |= temp;
699         }
700         return result;
701     }
702 
703     /**
704      * 将long整型数值转换为字节数组
705      * 
706      * @param num
707      * @return
708      */
709     public static byte[] longToBytes(long num) {
710         byte[] temp = new byte[8];
711         for (int i = 0; i < 8; i++) {
712             temp[i] = (byte) ((num >>> (56 - i * 8)) & 0xFF);
713         }
714         return temp;
715     }
716 
717     /**
718      * 将字节数组转换为long整型数值
719      * 
720      * @param arr
721      * @return
722      */
723     public static long bytesToLong(byte[] arr) {
724         int mask = 0xFF;
725         int temp = 0;
726         long result = 0;
727         int len = Math.min(8, arr.length);
728         for (int i = 0; i < len; i++) {
729             result <<= 8;
730             temp = arr[i] & mask;
731             result |= temp;
732         }
733         return result;
734     }
735 
736     /**
737      * 将16进制字符转换为字节
738      * 
739      * @param c
740      * @return
741      */
742     public static byte toByte(char c) {
743         byte b = (byte) "0123456789ABCDEF".indexOf(c);
744         return b;
745     }
746     
747     /**
748      * 功能描述:把两个字节的字节数组转化为整型数据,高位补零,例如:<br/>
749      * 有字节数组byte[] data = new byte[]{1,2};转换后int数据的字节分布如下:<br/>
750      * 00000000  00000000 00000001 00000010,函数返回258
751      * @param lenData 需要进行转换的字节数组
752      * @return  字节数组所表示整型值的大小
753      */
754     public static int bytesToIntWhereByteLengthEquals2(byte lenData[]) {
755         if(lenData.length != 2){
756             return -1;
757         }
758         byte fill[] = new byte[]{0,0};
759         byte real[] = new byte[4];
760         System.arraycopy(fill, 0, real, 0, 2);
761         System.arraycopy(lenData, 0, real, 2, 2);
762         int len = byteToInt(real);
763         return len;
764         
765     }
766     
767     /**
768      * 功能描述:将byte数组转化为int类型的数据
769      * @param byteVal 需要转化的字节数组
770      * @return 字节数组所表示的整型数据
771      */
772     public static int byteToInt(byte[] byteVal) {
773         int result = 0;
774         for(int i = 0;i < byteVal.length;i++) {
775             int tmpVal = (byteVal[i]<<(8*(3-i)));
776             switch(i) {
777                 case 0:
778                     tmpVal = tmpVal & 0xFF000000;
779                     break;
780                 case 1:
781                     tmpVal = tmpVal & 0x00FF0000;
782                     break;
783                 case 2:
784                     tmpVal = tmpVal & 0x0000FF00;
785                     break;
786                 case 3:
787                     tmpVal = tmpVal & 0x000000FF;
788                     break;
789             }
790         
791             result = result | tmpVal;
792         }
793         return result;
794     }
795     public static byte CheckXORSum(byte[] bData){
796         byte sum = 0x00;
797         for (int i = 0; i < bData.length; i++) {
798             sum ^= bData[i];
799         }
800         return sum;
801     }
802     /**
803      * 从offset开始 将后续长度为len的byte字节转为int
804      * @param data
805      * @param offset
806      * @param len
807      * @return
808      */
809     public static int bytesToInt(byte[] data, int offset, int len){
810         int mask = 0xFF;
811         int temp = 0;
812         int result = 0;
813         len = Math.min(len, 4);
814         for (int i = 0; i < len; i++) {
815             result <<= 8;
816             temp = data[offset + i] & mask;
817             result |= temp;
818         }
819         return result;
820     }
821     
822     /**
823      * byte字节数组中的字符串的长度
824      * @param data
825      * @return 
826      */
827     public static int getBytesStringLen(byte[] data)
828     {
829         int count = 0;
830         for (byte b : data) {
831             if(b == 0x00)
832                 break;
833             count++;
834         }
835         return count;
836     }
837     
838 }
原文地址:https://www.cnblogs.com/utank/p/7877761.html