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.openflowplugin.openflow.md.util;
10 import java.math.BigInteger;
11 import java.util.Arrays;
17 public abstract class ByteUtil {
22 * @return hexString containing bytes, separated with delimiter
24 public static String bytesToHexstring(final byte[] bytes, final String delimiter) {
25 StringBuffer sb = new StringBuffer();
26 for (byte b : bytes) {
27 sb.append(String.format("%02x%s", b, delimiter));
33 * Utility method to convert BigInteger to n element byte array
35 * @return byte array containing n * 8 bits.
37 public static byte[] convertBigIntegerToNBytes(final BigInteger bigInteger, final int numBytes) {
38 if (bigInteger == null) {
41 byte[] inputArray = bigInteger.toByteArray();
42 byte[] outputArray = new byte[numBytes];
43 if (bigInteger.compareTo(BigInteger.ZERO) < 0) {
44 Arrays.fill(outputArray, (byte) -1);
46 Arrays.fill(outputArray, (byte) 0);
48 System.arraycopy(inputArray,
49 Math.max(0, inputArray.length - outputArray.length),
51 Math.max(0, outputArray.length - inputArray.length),
52 Math.min(outputArray.length, inputArray.length));
57 * Converts a 4 byte array of unsigned bytes to unsigned int
58 * @param bytes an array of 4 unsigned bytes
59 * @return a long representing the unsigned int
61 public static final long bytesToUnsignedInt(final byte[] bytes)
64 unsignedInt |= bytes[0] & 0xFF;
66 unsignedInt |= bytes[1] & 0xFF;
68 unsignedInt |= bytes[2] & 0xFF;
70 unsignedInt |= bytes[3] & 0xFF;
75 * Converts a 2 byte array of unsigned bytes to unsigned short
76 * @param bytes an array of 2 unsigned bytes
77 * @return an int representing the unsigned short
79 public static final int bytesToUnsignedShort(final byte[] bytes)
81 int unsignedShort = 0;
82 unsignedShort |= bytes[0] & 0xFF;
84 unsignedShort |= bytes[1] & 0xFF;
89 * Converts unsigned integer to a 4 byte array of unsigned bytes
90 * @param unsignedInt representing the unsigned integer
91 * @return bytes an array of 4 unsigned bytes
93 public static byte[] unsignedIntToBytes(final Long unsignedInt)
95 byte[] bytes = new byte[4];
96 bytes[3] = (byte) (unsignedInt & 0xFF);
97 bytes[2] = (byte) ((unsignedInt >> 8) & 0xFF);
98 bytes[1] = (byte) ((unsignedInt >> 16) & 0xFF);
99 bytes[0] = (byte) ((unsignedInt >> 24) & 0xFF);
104 * Converts unsigned short to a 2 byte array of unsigned bytes
105 * @param unsignedShort representing the unsigned short
106 * @return bytes an array of 2 unsigned bytes
108 public static byte[] unsignedShortToBytes(final Integer unsignedShort)
110 byte[] bytes = new byte[2];
111 bytes[1] = (byte) (unsignedShort & 0xFF);
112 bytes[0] = (byte) ((unsignedShort >> 8) & 0xFF);