40b9be86960e457fb74c029a5c8b0fefc6226176
[bgpcep.git] / util / src / main / java / org / opendaylight / protocol / util / ByteArray.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.protocol.util;
9
10 import java.io.File;
11 import java.io.FileInputStream;
12 import java.io.IOException;
13 import java.nio.ByteBuffer;
14 import java.nio.charset.CharacterCodingException;
15 import java.nio.charset.Charset;
16 import java.util.Arrays;
17 import java.util.BitSet;
18
19 import org.apache.commons.codec.binary.Hex;
20
21 /**
22  * 
23  * Util class for methods working with byte array.
24  * 
25  */
26 public final class ByteArray {
27         private ByteArray() {
28         }
29
30         /**
31          * Returns a new byte array from given byte array, starting at start index with the size of the length parameter.
32          * Byte array given as parameter stays untouched.
33          * 
34          * @param bytes original byte array
35          * @param startIndex beginning index, inclusive
36          * @param length how many bytes should be in the sub-array
37          * @return a new byte array that is a sub-array of the original
38          */
39         public static byte[] subByte(final byte[] bytes, final int startIndex, final int length) {
40                 if (bytes.length == 0 || length < 0 || length > bytes.length || startIndex < 0 || startIndex > bytes.length
41                                 || startIndex + length > bytes.length) {
42                         throw new IllegalArgumentException("Cannot create subByte, invalid arguments: Length: " + length + " startIndex: " + startIndex);
43                 }
44                 final byte[] res = new byte[length];
45                 System.arraycopy(bytes, startIndex, res, 0, length);
46                 return res;
47         }
48
49         /**
50          * Converts byte array to Integer. If there are less bytes in the array as required (4), the method will push
51          * adequate number of zero bytes prepending given byte array.
52          * 
53          * @param bytes array to be converted to int
54          * @return int
55          */
56         public static int bytesToInt(final byte[] bytes) {
57                 if (bytes.length > Integer.SIZE / 8) {
58                         throw new IllegalArgumentException("Cannot convert bytes to integer. Byte array too big.");
59                 }
60                 byte[] res = new byte[Integer.SIZE / 8];
61                 if (bytes.length != Integer.SIZE / 8) {
62                         System.arraycopy(bytes, 0, res, Integer.SIZE / 8 - bytes.length, bytes.length);
63                 } else {
64                         res = bytes;
65                 }
66                 final ByteBuffer buff = ByteBuffer.wrap(res);
67                 return buff.getInt();
68         }
69
70         /**
71          * Converts byte array to long. If there are less bytes in the array as required (Long.Size), the method will push
72          * adequate number of zero bytes prepending given byte array.
73          * 
74          * @param bytes array to be converted to long
75          * @return long
76          */
77         public static long bytesToLong(final byte[] bytes) {
78                 if (bytes.length > Long.SIZE / 8) {
79                         throw new IllegalArgumentException("Cannot convert bytes to long.Byte array too big.");
80                 }
81                 byte[] res = new byte[Long.SIZE / 8];
82                 if (bytes.length != Long.SIZE / 8) {
83                         System.arraycopy(bytes, 0, res, Long.SIZE / 8 - bytes.length, bytes.length);
84                 } else {
85                         res = bytes;
86                 }
87                 final ByteBuffer buff = ByteBuffer.wrap(res);
88                 return buff.getLong();
89         }
90
91         /**
92          * Converts byte array to float IEEE 754 format. If there are less bytes in the array as required (Float.Size), the
93          * method will push adequate number of zero bytes prepending given byte array.
94          * 
95          * @param bytes array to be converted to float
96          * @return float
97          */
98         public static float bytesToFloat(final byte[] bytes) {
99                 if (bytes.length > Float.SIZE / 8) {
100                         throw new IllegalArgumentException("Cannot convert bytes to float.Byte array too big.");
101                 }
102                 byte[] res = new byte[Float.SIZE / 8];
103                 if (bytes.length != Float.SIZE / 8) {
104                         System.arraycopy(bytes, 0, res, Float.SIZE / 8 - bytes.length, bytes.length);
105                 } else {
106                         res = bytes;
107                 }
108                 final ByteBuffer buff = ByteBuffer.wrap(res);
109                 return buff.getFloat();
110         }
111
112         /**
113          * Cuts 'count' number of bytes from the beginning of given byte array.
114          * 
115          * @param bytes array to be cut, cannot be null
116          * @param count how many bytes needed to be cut, needs to be > 0
117          * @return bytes array without first 'count' bytes
118          */
119         public static byte[] cutBytes(final byte[] bytes, final int count) {
120                 if (bytes.length == 0 || count > bytes.length || count <= 0) {
121                         throw new IllegalArgumentException("Cannot cut bytes, invalid arguments: Count: " + count + " bytes.length: " + bytes.length);
122                 }
123                 return Arrays.copyOfRange(bytes, count, bytes.length);
124         }
125
126         /**
127          * Parse byte to bits, from the leftmost bit.
128          * 
129          * @param b byte to be parsed
130          * @return array of booleans with size of 8
131          */
132         public static boolean[] parseBits(final byte b) {
133                 final boolean[] bits = new boolean[Byte.SIZE];
134                 int j = 0;
135                 for (int i = Byte.SIZE - 1; i >= 0; i--) {
136                         bits[j] = ((b & (1 << i)) != 0);
137                         j++;
138                 }
139                 return bits;
140         }
141
142         /**
143          * Parses array of bytes to BitSet, from left most bit.
144          * 
145          * @param bytes array of bytes to be parsed
146          * @return BitSet with length = bytes.length * Byte.SIZE
147          */
148         public static BitSet bytesToBitSet(final byte[] bytes) {
149                 final BitSet bitSet = new BitSet(bytes.length * Byte.SIZE);
150                 for (int bytes_iter = 0; bytes_iter < bytes.length; bytes_iter++) {
151                         final int offset = bytes_iter * Byte.SIZE;
152                         for (int byte_iter = Byte.SIZE - 1; byte_iter >= 0; byte_iter--) {
153                                 bitSet.set(offset + (Byte.SIZE - byte_iter - 1), (bytes[bytes_iter] & 1 << (byte_iter)) != 0);
154                         }
155                 }
156                 return bitSet;
157         }
158
159         /**
160          * Parses BitSet to bytes, from most left bit.
161          * 
162          * @param bitSet BitSet to be parsed
163          * @param returnedLength Length of returned array. Overlapping flags are truncated.
164          * @return parsed array of bytes with length of bitSet.length / Byte.SIZE
165          */
166         public static byte[] bitSetToBytes(final BitSet bitSet, final int returnedLength) {
167                 final byte[] bytes = new byte[returnedLength];
168
169                 for (int bytes_iter = 0; bytes_iter < bytes.length; bytes_iter++) {
170                         final int offset = bytes_iter * Byte.SIZE;
171
172                         for (int byte_iter = Byte.SIZE - 1; byte_iter >= 0; byte_iter--) {
173                                 bytes[bytes_iter] |= (bitSet.get(offset + (Byte.SIZE - byte_iter - 1)) ? 1 << byte_iter : 0);
174                         }
175                 }
176                 return bytes;
177         }
178
179         /**
180          * Parses file to array of bytes
181          * 
182          * @param name path to file to by parsed
183          * @return parsed array of bytes
184          */
185         public static byte[] fileToBytes(final String name) throws IOException {
186                 final File file = new File(name);
187                 int offset = 0;
188                 int numRead = 0;
189
190                 if (file.length() > Integer.MAX_VALUE) {
191                         throw new IOException("Too large file to load in byte array.");
192                 }
193
194                 final FileInputStream fin = new FileInputStream(file);
195                 final byte[] byteArray = new byte[(int) file.length()];
196
197                 while (offset < byteArray.length && (numRead = fin.read(byteArray, offset, byteArray.length - offset)) >= 0) {
198                         offset += numRead;
199                 }
200
201                 if (fin != null) {
202                         fin.close();
203                 }
204
205                 return byteArray;
206         }
207
208         /**
209          * Parses integer to array of bytes
210          * 
211          * @param num integer to be parsed
212          * @return parsed array of bytes with length of Integer.SIZE/Byte.SIZE
213          */
214         public static byte[] intToBytes(final int num) {
215                 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
216                 bytesBuffer.putInt(num);
217
218                 return bytesBuffer.array();
219         }
220
221         /**
222          * Parses long to array of bytes
223          * 
224          * @param num long to be parsed
225          * @return parsed array of bytes with length of Long.SIZE/Byte.SIZE
226          */
227         public static byte[] longToBytes(final long num) {
228                 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
229                 bytesBuffer.putLong(num);
230
231                 return bytesBuffer.array();
232         }
233
234         /**
235          * Copies range of bits from passed byte and align to right.<br/>
236          * 
237          * @param src source byte to copy from
238          * @param fromBit bit from which will copy (inclusive) - numbered from 0
239          * @param length of bits to by copied - <1,8>
240          * @return copied value aligned to right
241          */
242         public static byte copyBitsRange(final byte src, final int fromBit, final int length) {
243                 if (fromBit < 0 | fromBit > Byte.SIZE - 1 | length < 1 | length > Byte.SIZE) {
244                         throw new IllegalArgumentException("fromBit or toBit is out of range.");
245                 }
246                 if (fromBit + length > Byte.SIZE) {
247                         throw new IllegalArgumentException("Out of range.");
248                 }
249
250                 byte retByte = 0;
251                 int retI = 0;
252
253                 for (int i = fromBit + length - 1; i >= fromBit; i--) {
254
255                         if ((src & 1 << (Byte.SIZE - i - 1)) != 0) {
256                                 retByte |= 1 << retI;
257                         }
258
259                         retI++;
260                 }
261
262                 return retByte;
263         }
264
265         /**
266          * Copies whole source byte array to destination from offset.<br/>
267          * Length of src can't be bigger than dest length minus offset
268          * 
269          * @param src byte[]
270          * @param dest byte[]
271          * @param offset int
272          */
273         public static void copyWhole(final byte[] src, final byte[] dest, final int offset) {
274                 if (dest.length - offset < src.length) {
275                         throw new ArrayIndexOutOfBoundsException("Can't copy whole array.");
276                 }
277
278                 System.arraycopy(src, 0, dest, offset, src.length);
279         }
280
281         /**
282          * Convert array of bytes to java short.<br/>
283          * Size can't be bigger than size of short in bytes.
284          * 
285          * @param bytes byte[]
286          * @return array of bytes
287          */
288         public static short bytesToShort(final byte[] bytes) {
289                 if (bytes.length > Short.SIZE / Byte.SIZE) {
290                         throw new IllegalArgumentException("Cannot convert bytes to short. Byte array too big.");
291                 }
292                 byte[] res = new byte[Short.SIZE / Byte.SIZE];
293                 if (bytes.length != Short.SIZE / Byte.SIZE) {
294                         System.arraycopy(bytes, 0, res, Integer.SIZE / Byte.SIZE - bytes.length, bytes.length);
295                 } else {
296                         res = bytes;
297                 }
298                 final ByteBuffer buff = ByteBuffer.wrap(res);
299                 return buff.getShort();
300         }
301
302         /**
303          * Convert short java representation to array of bytes.
304          * 
305          * @param num short
306          * @return short represented as array of bytes
307          */
308         public static byte[] shortToBytes(final short num) {
309                 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Short.SIZE / Byte.SIZE);
310                 bytesBuffer.putShort(num);
311
312                 return bytesBuffer.array();
313         }
314
315         /**
316          * Convert float java representation to array of bytes.
317          * 
318          * @param num float
319          * @return float represented as array of bytes
320          */
321         public static byte[] floatToBytes(final float num) {
322                 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Float.SIZE / Byte.SIZE);
323                 bytesBuffer.putFloat(num);
324
325                 return bytesBuffer.array();
326         }
327
328         /**
329          * Pretty print array of bytes as hex encoded string with 16 bytes per line. Each byte is separated by space, after
330          * first 8 bytes there are 2 spaces instead of one.
331          */
332         public static String bytesToHexString(final byte[] array) {
333                 return bytesToHexString(array, 16, " ", 8, " ");
334         }
335
336         /**
337          * Pretty-print an array of bytes as hex-encoded string. Separate them with specified separator.
338          */
339         public static String toHexString(final byte[] array, final String separator) {
340                 final StringBuilder sb = new StringBuilder();
341                 for (int i = 0; i < array.length; i++) {
342                         sb.append(Hex.encodeHexString(new byte[] { array[i] }));
343                         if (i + 1 != array.length) {
344                                 sb.append(separator);
345                         }
346                 }
347                 return sb.toString();
348         }
349
350         /**
351          * Convert array of bytes to hexadecimal String.
352          * 
353          * @param array
354          * @param bytesOnLine number of bytes that should by displayed in one line
355          * @param byteSeparator string that will be placed after each byte
356          * @param wordCount number of bytes that make a 'word' (group of bytes)
357          * @param wordSeparator string that will be placed after each word
358          * @return Hexadecimal string representation of given byte array
359          */
360         public static String bytesToHexString(final byte[] array, final int bytesOnLine, final String byteSeparator, final int wordCount,
361                         final String wordSeparator) {
362                 final StringBuilder sb = new StringBuilder();
363                 for (int i = 0; i < array.length; i++) {
364                         sb.append(Hex.encodeHexString(new byte[] { array[i] }));
365                         if ((i + 1) % bytesOnLine == 0) {
366                                 sb.append("\n");
367                         } else {
368                                 sb.append(byteSeparator);
369                                 if ((i + 1) % wordCount == 0) {
370                                         sb.append(wordSeparator);
371                                 }
372                         }
373
374                 }
375                 return sb.toString();
376         }
377
378         /**
379          * Decodes bytes to human readable UTF-8 string. If bytes are not valid UTF-8, they are represented as raw binary.
380          * 
381          * @param bytes bytes to be decoded to string
382          * @return String representation of passed bytes
383          */
384         public static String bytesToHRString(final byte[] bytes) {
385                 try {
386                         return Charset.forName("UTF-8").newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
387                 } catch (final CharacterCodingException e) {
388                         return Arrays.toString(bytes);
389                 }
390         }
391
392         /**
393          * Searches for byte sequence in given array. Returns the index of first occurrence of this sequence (where it
394          * starts).
395          * 
396          * @param bytes byte array where to search for sequence
397          * @param sequence to be searched in given byte array
398          * @return -1 if the sequence could not be found in given byte array int index of first occurrence of the sequence
399          *         in bytes
400          */
401         public static int findByteSequence(final byte[] bytes, final byte[] sequence) {
402                 if (bytes.length < sequence.length) {
403                         throw new IllegalArgumentException("Sequence to be found is longer than the given byte array.");
404                 }
405                 if (bytes.length == sequence.length) {
406                         if (Arrays.equals(bytes, sequence)) {
407                                 return 0;
408                         } else {
409                                 return -1;
410                         }
411                 }
412                 int j = 0;
413                 for (int i = 0; i < bytes.length; i++) {
414                         if (bytes[i] == sequence[j]) {
415                                 j++;
416                                 if (j == sequence.length) {
417                                         return i - j + 1;
418                                 }
419                         } else {
420                                 j = 0;
421                         }
422                 }
423                 return -1;
424         }
425
426         private static final byte maskBits[] = new byte[] { 0, -128, -64, -32, -16, -8, -4, -2 };
427
428         public static final byte[] maskBytes(final byte[] original, final int bits) {
429                 if (original.length * 8 < bits) {
430                         throw new IllegalArgumentException("Attempted to apply invalid mask (too long)");
431                 }
432
433                 final int needbytes = (bits + 7) / 8;
434                 // We need to have a new copy of the underlying byte array, so that
435                 // the original bytes stay untouched
436                 final byte[] bytes = Arrays.copyOf(original, original.length);
437
438                 final int needmask = bits % 8;
439                 if (needmask != 0) {
440                         bytes[needbytes - 1] &= maskBits[needmask];
441                 }
442
443                 // zero-out the rest of the bytes
444                 for (int i = needbytes; i < bytes.length; i++) {
445                         bytes[i] = 0;
446                 }
447                 return bytes;
448         }
449 }