]> git.basschouten.com Git - openhab-addons.git/blob
e2da533cbec9118af95a623352b96d5b94922974
[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.folderwatcher.internal.api.util;
14
15 import java.util.Locale;
16
17 import org.eclipse.jdt.annotation.NonNullByDefault;
18
19 /**
20  * The {@link BinaryUtils} class contains methods for binary interactions.
21  * <p>
22  * Based on offical AWS example {@see https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-examples-using-sdks.html}
23  * 
24  * @author Alexandr Salamatov - Initial contribution
25  */
26 @NonNullByDefault
27 public class BinaryUtils {
28     public static String toHex(byte[] data) {
29         StringBuilder sb = new StringBuilder(data.length * 2);
30         for (int i = 0; i < data.length; i++) {
31             String hex = Integer.toHexString(data[i]);
32             if (hex.length() == 1) {
33                 sb.append("0");
34             } else if (hex.length() == 8) {
35                 hex = hex.substring(6);
36             }
37             sb.append(hex);
38         }
39         return sb.toString().toLowerCase(Locale.getDefault());
40     }
41
42     public static byte[] fromHex(String hexData) {
43         byte[] result = new byte[(hexData.length() + 1) / 2];
44         String hexNumber = null;
45         int stringOffset = 0;
46         int byteOffset = 0;
47         while (stringOffset < hexData.length()) {
48             hexNumber = hexData.substring(stringOffset, stringOffset + 2);
49             stringOffset += 2;
50             result[byteOffset++] = (byte) Integer.parseInt(hexNumber, 16);
51         }
52         return result;
53     }
54 }