Jian Li | 4767190 | 2016-08-11 01:18:18 +0900 | [diff] [blame] | 1 | /* |
| 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 | */ |
| 16 | package org.onlab.util; |
| 17 | |
| 18 | /** |
| 19 | * Provide a set of byte operations. |
| 20 | */ |
| 21 | public 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 | */ |
Jian Li | e4ba2a4 | 2016-08-29 20:24:15 +0900 | [diff] [blame] | 64 | public static int getHex(int decimal) { |
Jian Li | 4767190 | 2016-08-11 01:18:18 +0900 | [diff] [blame] | 65 | return Integer.valueOf(String.valueOf(decimal), 16); |
| 66 | } |
| 67 | } |