]> git.basschouten.com Git - openhab-addons.git/blob
8e29015440c41f5e6ab40574cdb984ab6b0278d7
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.lcn.internal.common;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 /**
18  * Helper to bitwise reverse numbers.
19  *
20  * @author Tobias Jüttner - Initial Contribution
21  */
22 @NonNullByDefault
23 final class ReverseNumber {
24     /** Cache with all reversed 8 bit values. */
25     private static final int[] REVERSED_UINT8 = new int[256];
26
27     /** Initializes static data once this class is first used. */
28     static {
29         for (int i = 0; i < 256; ++i) {
30             int reversed = 0;
31             for (int j = 0; j < 8; ++j) {
32                 if ((i & (1 << j)) != 0) {
33                     reversed |= (0x80 >> j);
34                 }
35             }
36             REVERSED_UINT8[i] = reversed;
37         }
38     }
39
40     /**
41      * Reverses the given 8 bit value bitwise.
42      *
43      * @param value the value to reverse bitwise (treated as unsigned 8 bit value)
44      * @return the reversed value
45      * @throws LcnException if value is out of range (not unsigned 8 bit)
46      */
47     static int reverseUInt8(int value) throws LcnException {
48         if (value < 0 || value > 255) {
49             throw new LcnException();
50         }
51         return REVERSED_UINT8[value];
52     }
53 }