View Javadoc
1   /*******************************************************************************
2    * jArduino: Arduino C++ Code Generation From Java
3    * Copyright 2020 Tony Washer
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    *   http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   ******************************************************************************/
17  package net.sourceforge.jarduino.util;
18  
19  /**
20   *  Hex utilities.
21   */
22  public final class ArduinoHex {
23      /**
24       * Byte mask.
25       */
26      public static final int BYTE_MASK = 0xFF;
27  
28      /**
29       * Nybble mask.
30       */
31      public static final int NYBBLE_MASK = 0xF;
32  
33      /**
34       * Nybble shift.
35       */
36      public static final int NYBBLE_SHIFT = Byte.SIZE >> 1;
37  
38      /**
39       * Hexadecimal Radix.
40       */
41      public static final int HEX_RADIX = 16;
42  
43      /**
44       * Private constrructor.
45       */
46      private ArduinoHex() {
47      }
48  
49      /**
50       * format a byte array as a hexadecimal string.
51       * @param pBytes the byte array
52       * @return the string
53       */
54      public static String bytesToHexString(final byte[] pBytes) {
55          /* Allocate the string builder */
56          final StringBuilder myValue = new StringBuilder(2 * pBytes.length);
57  
58          /* For each byte in the value */
59          for (final byte b : pBytes) {
60              /* Access the byte as an unsigned integer */
61              int myInt = (int) b;
62              if (myInt < 0) {
63                  myInt += BYTE_MASK + 1;
64              }
65  
66              /* Access the high nybble */
67              int myDigit = myInt >>> NYBBLE_SHIFT;
68              char myChar = Character.forDigit(myDigit, HEX_RADIX);
69  
70              /* Add it to the value string */
71              myValue.append(myChar);
72  
73              /* Access the low digit */
74              myDigit = myInt
75                      & NYBBLE_MASK;
76              myChar = Character.forDigit(myDigit, HEX_RADIX);
77  
78              /* Add it to the value string */
79              myValue.append(myChar);
80          }
81  
82          /* Return the string */
83          return myValue.toString();
84      }
85  }