ArduinoHex.java
/*******************************************************************************
* jArduino: Arduino C++ Code Generation From Java
* Copyright 2020 Tony Washer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package net.sourceforge.jarduino.util;
/**
* Hex utilities.
*/
public final class ArduinoHex {
/**
* Byte mask.
*/
public static final int BYTE_MASK = 0xFF;
/**
* Nybble mask.
*/
public static final int NYBBLE_MASK = 0xF;
/**
* Nybble shift.
*/
public static final int NYBBLE_SHIFT = Byte.SIZE >> 1;
/**
* Hexadecimal Radix.
*/
public static final int HEX_RADIX = 16;
/**
* Private constrructor.
*/
private ArduinoHex() {
}
/**
* format a byte array as a hexadecimal string.
* @param pBytes the byte array
* @return the string
*/
public static String bytesToHexString(final byte[] pBytes) {
/* Allocate the string builder */
final StringBuilder myValue = new StringBuilder(2 * pBytes.length);
/* For each byte in the value */
for (final byte b : pBytes) {
/* Access the byte as an unsigned integer */
int myInt = (int) b;
if (myInt < 0) {
myInt += BYTE_MASK + 1;
}
/* Access the high nybble */
int myDigit = myInt >>> NYBBLE_SHIFT;
char myChar = Character.forDigit(myDigit, HEX_RADIX);
/* Add it to the value string */
myValue.append(myChar);
/* Access the low digit */
myDigit = myInt
& NYBBLE_MASK;
myChar = Character.forDigit(myDigit, HEX_RADIX);
/* Add it to the value string */
myValue.append(myChar);
}
/* Return the string */
return myValue.toString();
}
}