2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.protocol.util;
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;
19 import org.apache.commons.codec.binary.Hex;
23 * Util class for methods working with byte array.
26 public final class ByteArray {
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.
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
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);
44 final byte[] res = new byte[length];
45 System.arraycopy(bytes, startIndex, res, 0, length);
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.
53 * @param bytes array to be converted to int
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.");
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);
66 final ByteBuffer buff = ByteBuffer.wrap(res);
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.
74 * @param bytes array to be converted to long
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.");
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);
87 final ByteBuffer buff = ByteBuffer.wrap(res);
88 return buff.getLong();
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.
95 * @param bytes array to be converted to float
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.");
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);
108 final ByteBuffer buff = ByteBuffer.wrap(res);
109 return buff.getFloat();
113 * Cuts 'count' number of bytes from the beginning of given byte array.
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
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);
123 return Arrays.copyOfRange(bytes, count, bytes.length);
127 * Parse byte to bits, from the leftmost bit.
129 * @param b byte to be parsed
130 * @return array of booleans with size of 8
132 public static boolean[] parseBits(final byte b) {
133 final boolean[] bits = new boolean[Byte.SIZE];
135 for (int i = Byte.SIZE - 1; i >= 0; i--) {
136 bits[j] = ((b & (1 << i)) != 0);
143 * Parses array of bytes to BitSet, from left most bit.
145 * @param bytes array of bytes to be parsed
146 * @return BitSet with length = bytes.length * Byte.SIZE
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);
160 * Parses BitSet to bytes, from most left bit.
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
166 public static byte[] bitSetToBytes(final BitSet bitSet, final int returnedLength) {
167 final byte[] bytes = new byte[returnedLength];
169 for (int bytes_iter = 0; bytes_iter < bytes.length; bytes_iter++) {
170 final int offset = bytes_iter * Byte.SIZE;
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);
180 * Parses file to array of bytes
182 * @param name path to file to by parsed
183 * @return parsed array of bytes
185 public static byte[] fileToBytes(final String name) throws IOException {
186 final File file = new File(name);
190 if (file.length() > Integer.MAX_VALUE) {
191 throw new IOException("Too large file to load in byte array.");
194 final FileInputStream fin = new FileInputStream(file);
195 final byte[] byteArray = new byte[(int) file.length()];
197 while (offset < byteArray.length && (numRead = fin.read(byteArray, offset, byteArray.length - offset)) >= 0) {
209 * Parses integer to array of bytes
211 * @param num integer to be parsed
212 * @return parsed array of bytes with length of Integer.SIZE/Byte.SIZE
214 public static byte[] intToBytes(final int num) {
215 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Integer.SIZE / Byte.SIZE);
216 bytesBuffer.putInt(num);
218 return bytesBuffer.array();
222 * Parses long to array of bytes
224 * @param num long to be parsed
225 * @return parsed array of bytes with length of Long.SIZE/Byte.SIZE
227 public static byte[] longToBytes(final long num) {
228 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Long.SIZE / Byte.SIZE);
229 bytesBuffer.putLong(num);
231 return bytesBuffer.array();
235 * Copies range of bits from passed byte and align to right.<br/>
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
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.");
246 if (fromBit + length > Byte.SIZE) {
247 throw new IllegalArgumentException("Out of range.");
253 for (int i = fromBit + length - 1; i >= fromBit; i--) {
255 if ((src & 1 << (Byte.SIZE - i - 1)) != 0) {
256 retByte |= 1 << retI;
266 * Copies whole source byte array to destination from offset.<br/>
267 * Length of src can't be bigger than dest length minus offset
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.");
278 System.arraycopy(src, 0, dest, offset, src.length);
282 * Convert array of bytes to java short.<br/>
283 * Size can't be bigger than size of short in bytes.
285 * @param bytes byte[]
286 * @return array of bytes
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.");
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);
298 final ByteBuffer buff = ByteBuffer.wrap(res);
299 return buff.getShort();
303 * Convert short java representation to array of bytes.
306 * @return short represented as array of bytes
308 public static byte[] shortToBytes(final short num) {
309 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Short.SIZE / Byte.SIZE);
310 bytesBuffer.putShort(num);
312 return bytesBuffer.array();
316 * Convert float java representation to array of bytes.
319 * @return float represented as array of bytes
321 public static byte[] floatToBytes(final float num) {
322 final ByteBuffer bytesBuffer = ByteBuffer.allocate(Float.SIZE / Byte.SIZE);
323 bytesBuffer.putFloat(num);
325 return bytesBuffer.array();
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.
332 public static String bytesToHexString(final byte[] array) {
333 return bytesToHexString(array, 16, " ", 8, " ");
337 * Pretty-print an array of bytes as hex-encoded string. Separate them with specified separator.
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);
347 return sb.toString();
351 * Convert array of bytes to hexadecimal String.
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
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) {
368 sb.append(byteSeparator);
369 if ((i + 1) % wordCount == 0) {
370 sb.append(wordSeparator);
375 return sb.toString();
379 * Decodes bytes to human readable UTF-8 string. If bytes are not valid UTF-8, they are represented as raw binary.
381 * @param bytes bytes to be decoded to string
382 * @return String representation of passed bytes
384 public static String bytesToHRString(final byte[] bytes) {
386 return Charset.forName("UTF-8").newDecoder().decode(ByteBuffer.wrap(bytes)).toString();
387 } catch (final CharacterCodingException e) {
388 return Arrays.toString(bytes);
393 * Searches for byte sequence in given array. Returns the index of first occurrence of this sequence (where it
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
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.");
405 if (bytes.length == sequence.length) {
406 if (Arrays.equals(bytes, sequence)) {
413 for (int i = 0; i < bytes.length; i++) {
414 if (bytes[i] == sequence[j]) {
416 if (j == sequence.length) {
426 private static final byte maskBits[] = new byte[] { 0, -128, -64, -32, -16, -8, -4, -2 };
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)");
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);
438 final int needmask = bits % 8;
440 bytes[needbytes - 1] &= maskBits[needmask];
443 // zero-out the rest of the bytes
444 for (int i = needbytes; i < bytes.length; i++) {