2 * Copyright (c) 2014 Contextream, 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
9 package org.opendaylight.lispflowmapping.lisp.util;
11 import java.nio.ByteBuffer;
13 public final class ByteUtil {
15 protected static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
17 // Utility class, should not be instantiated
21 public static int getUnsignedByte(byte[] inBuffer, int pos) {
22 return inBuffer[pos] & 0xFF;
25 public static int getUnsignedByte(ByteBuffer inBuffer, int pos) {
26 return inBuffer.get(pos) & 0xFF;
29 public static int getUnsignedByte(ByteBuffer inBuffer) {
30 return inBuffer.get() & 0xFF;
33 public static int getUnsignedShort(byte[] inBuffer, int pos) {
34 return asUnsignedShort(getShort(inBuffer, pos));
37 public static int getUnsignedShort(ByteBuffer inBuffer, int pos) {
38 return asUnsignedShort(inBuffer.getShort(pos));
41 public static short getShort(byte[] inBuffer, int pos) {
42 return ByteBuffer.wrap(inBuffer, pos, 2).getShort();
45 public static int getInt(byte[] inBuffer, int pos) {
46 return ByteBuffer.wrap(inBuffer, pos, 4).getInt();
49 public static int getPartialInt(byte[] inBuffer) {
50 ByteBuffer buffer = ByteBuffer.allocate(4);
51 buffer.position(4 - inBuffer.length);
54 return buffer.getInt();
57 public static short asUnsignedByte(byte byteArg) {
58 return (short) ((short) byteArg & 0xFF);
61 public static int asUnsignedShort(short shortArg) {
62 return shortArg & 0xFFFF;
65 public static long asUnsignedInteger(int intArg) {
66 return intArg & 0xFFFFFFFF;
69 public static byte[] partialIntToByteArray(int number, int length) {
70 ByteBuffer buffer = ByteBuffer.allocate(4);
71 buffer.putInt(number);
72 byte[] result = new byte[length];
73 buffer.position(4 - length);
78 public static long getLong(byte[] inBuffer, int pos) {
79 return ByteBuffer.wrap(inBuffer, pos, 8).getLong();
82 public static boolean extractBit(byte byteValue, int bitMask) {
83 return (byteValue & bitMask) == bitMask;
86 public static byte boolToBit(boolean flag, int bit) {
87 return (byte) (flag ? bit : 0x00);
90 public static String bytesToHex(byte[] bytes, int length) {
91 char[] hexChars = new char[length * 2];
92 for (int j = 0; j < length; j++) {
93 int vv = bytes[j] & 0xFF;
94 hexChars[j * 2] = HEX_ARRAY[vv >>> 4];
95 hexChars[j * 2 + 1] = HEX_ARRAY[vv & 0x0F];
97 return new String(hexChars);