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 class ByteUtil {
15 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
17 public static int getUnsignedByte(byte[] inBuffer, int pos) {
18 return inBuffer[pos] & 0xFF;
21 public static int getUnsignedByte(ByteBuffer inBuffer, int pos) {
22 return inBuffer.get(pos) & 0xFF;
25 public static int getUnsignedByte(ByteBuffer inBuffer) {
26 return inBuffer.get() & 0xFF;
29 public static int getUnsignedShort(byte[] inBuffer, int pos) {
30 return asUnsignedShort(getShort(inBuffer, pos));
33 public static int getUnsignedShort(ByteBuffer inBuffer, int pos) {
34 return asUnsignedShort(inBuffer.getShort(pos));
37 public static short getShort(byte[] inBuffer, int pos) {
38 return ByteBuffer.wrap(inBuffer, pos, 2).getShort();
41 public static int getInt(byte[] inBuffer, int pos) {
42 return ByteBuffer.wrap(inBuffer, pos, 4).getInt();
45 public static int getPartialInt(byte[] inBuffer) {
46 ByteBuffer buffer = ByteBuffer.allocate(4);
47 buffer.position(4 - inBuffer.length);
50 return buffer.getInt();
53 public static short asUnsignedByte(byte b) {
54 return (short) ((short) b & 0xFF);
57 public static int asUnsignedShort(short s) {
61 public static long asUnsignedInteger(int i) {
62 return i & 0xFFFFFFFF;
65 public static byte[] partialIntToByteArray(int number, int length) {
66 ByteBuffer buffer = ByteBuffer.allocate(4);
67 buffer.putInt(number);
68 byte[] result = new byte[length];
69 buffer.position(4 - length);
74 public static long getLong(byte[] inBuffer, int pos) {
75 return ByteBuffer.wrap(inBuffer, pos, 8).getLong();
78 public static boolean extractBit(byte byteValue, int bitMask) {
79 return (byteValue & bitMask) == bitMask;
82 public static byte boolToBit(boolean flag, int bit) {
83 return (byte) (flag ? bit : 0x00);
86 public static String bytesToHex(byte[] bytes, int length) {
87 char[] hexChars = new char[length * 2];
88 for ( int j = 0; j < length; j++ ) {
89 int v = bytes[j] & 0xFF;
90 hexChars[j * 2] = hexArray[v >>> 4];
91 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
93 return new String(hexChars);