com.unstoppabledomains.resolutionNumeric Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of unstoppable-resolution Show documentation
Show all versions of unstoppable-resolution Show documentation
Resolution library that talks with etherium .crypto registry to resolve various information attached to .crypto domain
package com.unstoppabledomains.resolution.artifacts;
/** This code was taken from web3J and adapted accordingly
* https://github.com/web3j/web3j/blob/5877c308e11c0de8e24e50c882effa84354a8e57/utils/src/main/java/org/web3j/utils/Numeric.java#L27
*/
public final class Numeric {
private Numeric() {}
public static String cleanHexPrefix(String input) {
if (containsHexPrefix(input)) {
return input.substring(2);
} else {
return input;
}
}
public static boolean containsHexPrefix(String input) {
return !Strings.isEmpty(input)
&& input.length() > 1
&& input.charAt(0) == '0'
&& input.charAt(1) == 'x';
}
public static byte[] hexStringToByteArray(String input) {
String cleanInput = cleanHexPrefix(input);
int len = cleanInput.length();
if (len == 0) {
return new byte[] {};
}
byte[] data;
int startIdx;
if (len % 2 != 0) {
data = new byte[(len / 2) + 1];
data[0] = (byte) Character.digit(cleanInput.charAt(0), 16);
startIdx = 1;
} else {
data = new byte[len / 2];
startIdx = 0;
}
for (int i = startIdx; i < len; i += 2) {
data[(i + 1) / 2] =
(byte)
((Character.digit(cleanInput.charAt(i), 16) << 4)
+ Character.digit(cleanInput.charAt(i + 1), 16));
}
return data;
}
public static String toHexString(byte[] input, int offset, int length, boolean withPrefix) {
StringBuilder stringBuilder = new StringBuilder();
if (withPrefix) {
stringBuilder.append("0x");
}
for (int i = offset; i < offset + length; i++) {
stringBuilder.append(String.format("%02x", input[i] & 0xFF));
}
return stringBuilder.toString();
}
public static String toHexString(byte[] input) {
return toHexString(input, 0, input.length, true);
}
}