stringToBytes: comments2

This commit is contained in:
nick 2023-11-27 18:24:22 +02:00
parent ee8dd9f987
commit 3af8b1a33e

View File

@ -213,18 +213,16 @@ public class TbUtils {
private static byte[] bytesFromList(List<?> bytesList) { private static byte[] bytesFromList(List<?> bytesList) {
byte[] bytes = new byte[bytesList.size()]; byte[] bytes = new byte[bytesList.size()];
for (int i = 0; i < bytesList.size(); i++) { for (int i = 0; i < bytesList.size(); i++) {
if (bytesList.get(i) instanceof Integer) { Object objectVal = bytesList.get(i);
byte val = ((Integer) bytesList.get(i)).byteValue(); if (objectVal instanceof Integer) {
if (((Integer) bytesList.get(i)).intValue() > 255 || ((Integer) bytesList.get(i)).intValue() < -128){ bytes[i] = isValidIntegerToByte((Integer) objectVal);
throw new NumberFormatException("The value " + bytesList.get(i) + " could not be converted to a byte. Integer to byte needs only 8-bits (min/max = -128/127 or 0/255) !"); } else if (objectVal instanceof String) {
bytes[i] = isValidIntegerToByte(parseInt((String) objectVal));
} else if (objectVal instanceof Byte) {
bytes[i] = (byte) objectVal;
} else { } else {
bytes[i] = val; } throw new NumberFormatException("The value '" + objectVal + "' could not be correctly converted to a byte. " +
} else if (bytesList.get(i) instanceof String) { "Must be a HexDecimal/String/Integer/Byte format !");
bytes[i] = parseInt((String) bytesList.get(i)).byteValue();
} else if (bytesList.get(i) instanceof Byte) {
bytes[i] = (byte) bytesList.get(i);
} else {
throw new NumberFormatException("Value \"" + bytesList.get(i) + " could not be converted to a byte. Must be format HexDecimal/String/Integer !");
} }
} }
return bytes; return bytes;
@ -655,7 +653,7 @@ public class TbUtils {
} }
} }
public static boolean isValidRadix(String value, int radix) { private static boolean isValidRadix(String value, int radix) {
for (int i = 0; i < value.length(); i++) { for (int i = 0; i < value.length(); i++) {
if (i == 0 && value.charAt(i) == '-') { if (i == 0 && value.charAt(i) == '-') {
if (value.length() == 1) if (value.length() == 1)
@ -669,4 +667,12 @@ public class TbUtils {
return true; return true;
} }
private static byte isValidIntegerToByte (Integer val) {
if (val > 255 || val.intValue() < -128) {
throw new NumberFormatException("The value '" + val + "' could not be correctly converted to a byte. " +
"Integer to byte conversion requires the use of only 8 bits (with a range of min/max = -128/255)!");
} else {
return val.byteValue();
}
}
} }