1
2
3
4
5
6
7
8
9 package org.opendaylight.lispflowmapping.lisp.util;
10
11 import java.nio.ByteBuffer;
12
13 public final class ByteUtil {
14
15 final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
16
17
18 private ByteUtil() {
19 }
20
21 public static int getUnsignedByte(byte[] inBuffer, int pos) {
22 return inBuffer[pos] & 0xFF;
23 }
24
25 public static int getUnsignedByte(ByteBuffer inBuffer, int pos) {
26 return inBuffer.get(pos) & 0xFF;
27 }
28
29 public static int getUnsignedByte(ByteBuffer inBuffer) {
30 return inBuffer.get() & 0xFF;
31 }
32
33 public static int getUnsignedShort(byte[] inBuffer, int pos) {
34 return asUnsignedShort(getShort(inBuffer, pos));
35 }
36
37 public static int getUnsignedShort(ByteBuffer inBuffer, int pos) {
38 return asUnsignedShort(inBuffer.getShort(pos));
39 }
40
41 public static short getShort(byte[] inBuffer, int pos) {
42 return ByteBuffer.wrap(inBuffer, pos, 2).getShort();
43 }
44
45 public static int getInt(byte[] inBuffer, int pos) {
46 return ByteBuffer.wrap(inBuffer, pos, 4).getInt();
47 }
48
49 public static int getPartialInt(byte[] inBuffer) {
50 ByteBuffer buffer = ByteBuffer.allocate(4);
51 buffer.position(4 - inBuffer.length);
52 buffer.put(inBuffer);
53 buffer.position(0);
54 return buffer.getInt();
55 }
56
57 public static short asUnsignedByte(byte b) {
58 return (short) ((short) b & 0xFF);
59 }
60
61 public static int asUnsignedShort(short s) {
62 return s & 0xFFFF;
63 }
64
65 public static long asUnsignedInteger(int i) {
66 return i & 0xFFFFFFFF;
67 }
68
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);
74 buffer.get(result);
75 return result;
76 }
77
78 public static long getLong(byte[] inBuffer, int pos) {
79 return ByteBuffer.wrap(inBuffer, pos, 8).getLong();
80 }
81
82 public static boolean extractBit(byte byteValue, int bitMask) {
83 return (byteValue & bitMask) == bitMask;
84 }
85
86 public static byte boolToBit(boolean flag, int bit) {
87 return (byte) (flag ? bit : 0x00);
88 }
89
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 v = bytes[j] & 0xFF;
94 hexChars[j * 2] = hexArray[v >>> 4];
95 hexChars[j * 2 + 1] = hexArray[v & 0x0F];
96 }
97 return new String(hexChars);
98 }
99 }