]> git.basschouten.com Git - openhab-addons.git/blob
4742ecfd8d3ab0ce02efc05817412c82c339694c
[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.echonetlite.internal;
14
15 import java.nio.ByteBuffer;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * @author Michael Barker - Initial contribution
21  */
22 @NonNullByDefault
23 public class HexUtil {
24     public static String hex(ByteBuffer buffer) {
25         return hex(buffer, "[", "]", "0x", ",");
26     }
27
28     public static String hex(final ByteBuffer buffer, final String stringPrefix, final String stringSuffix,
29             final String bytePrefix, final String delimiter) {
30         final StringBuilder sb = new StringBuilder();
31         sb.append(stringPrefix);
32         for (int i = buffer.position(), n = buffer.limit(); i < n; i++) {
33             final int b = buffer.get(i) & 0xFF;
34             final String prefix = b < 0x10 ? "0" : "";
35             sb.append(bytePrefix).append(prefix).append(Integer.toHexString(b)).append(delimiter);
36         }
37         sb.setLength(sb.length() - delimiter.length());
38         sb.append(stringSuffix);
39
40         return sb.toString();
41     }
42
43     public static String hex(int[] array, int offset, int length) {
44         final StringBuilder sb = new StringBuilder();
45         sb.append('[');
46         for (int i = offset; i < length; i++) {
47             final int b = array[i] & 0xFF;
48             hex(sb, b);
49             sb.append(',');
50         }
51         sb.setLength(sb.length() - 1);
52         sb.append(']');
53
54         return sb.toString();
55     }
56
57     private static void hex(final StringBuilder sb, final int b) {
58         final String prefix = b < 0x10 ? "0" : "";
59         sb.append("0x").append(prefix).append(Integer.toHexString(b));
60     }
61
62     public static String hex(final int b) {
63         final StringBuilder sb = new StringBuilder();
64         hex(sb, b);
65         return sb.toString();
66     }
67
68     public static String hex(int[] array) {
69         return hex(array, 0, array.length);
70     }
71 }