blob: 4d30ce746ff6a01f4a3b3ef7e895d00eea44de42 [file] [log] [blame]
Jian Li47671902016-08-11 01:18:18 +09001/*
2 * Copyright 2016-present Open Networking Laboratory
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onlab.util;
17
18/**
19 * Provide a set of byte operations.
20 */
21public final class ByteOperator {
22
23 /**
24 * Private constructor which prevents from external instantiation.
25 */
26 private ByteOperator() {
27
28 }
29
30 /**
31 * Obtains a specific bit value from a byte with given index number.
32 *
33 * @param value byte value
34 * @param index index number
35 * @return a specific bit value from a byte
36 */
37 public static boolean getBit(byte value, int index) {
38 // the length of byte should always be positive whiles less than 8
39 if (index > 7 || index < 0) {
40 return false;
41 }
42
43 int bitMask = getHex((int) Math.pow(2, index));
44 return (value & bitMask) == bitMask;
45 }
46
47 /**
48 * Converts boolean value into bit.
49 *
50 * @param value boolean value
51 * @param bit bit value
52 * @return converted bit value
53 */
54 public static byte toBit(boolean value, int bit) {
55 return (byte) (value ? bit : 0x00);
56 }
57
58 /**
59 * Convert decimal integer into hex integer.
60 *
61 * @param decimal decimal formatted integer
62 * @return hex formatted integer
63 */
64 private static int getHex(int decimal) {
65 return Integer.valueOf(String.valueOf(decimal), 16);
66 }
67}