Kotlin conversion: HexUtil

This commit is contained in:
Paul Schaub 2023-10-31 15:00:21 +01:00
parent 01f98df80b
commit b7007cc007
Signed by: vanitasvitae
GPG Key ID: 62BEE9264BF17311
2 changed files with 38 additions and 47 deletions

View File

@ -1,47 +0,0 @@
// Copyright 2021 Paul Schaub, @maybeWeCouldStealAVan, @Dave L.
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util;
public class HexUtil {
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
/**
* Encode a byte array to a hex string.
*
* @see <a href="https://stackoverflow.com/a/9855338">
* How to convert a byte array to a hex string in Java?</a>
* @param bytes bytes
* @return hex encoding
*/
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
/**
* Decode a hex string into a byte array.
*
* @see <a href="https://stackoverflow.com/a/140861">
* Convert a string representation of a hex dump to a byte array using Java?</a>
* @param s hex string
* @return decoded byte array
*/
public static byte[] hexToBytes(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}

View File

@ -0,0 +1,38 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.util
class HexUtil {
companion object {
/**
* Encode a byte array to a hex string.
*
* @param bytes bytes
* @return hex encoding
* @see
* [Convert Byte Arrays to Hex Strings in Kotlin](https://www.baeldung.com/kotlin/byte-arrays-to-hex-strings)
*/
@JvmStatic fun bytesToHex(bytes: ByteArray): String = bytes.toHex()
/**
* Decode a hex string into a byte array.
*
* @param s hex string
* @return decoded byte array
* @see
* [Kotlin convert hex string to ByteArray](https://stackoverflow.com/a/66614516/11150851)
*/
@JvmStatic fun hexToBytes(s: String): ByteArray = s.decodeHex()
}
}
fun String.decodeHex(): ByteArray {
check(length % 2 == 0) { "Hex encoding must have even number of digits." }
return chunked(2).map { it.toInt(16).toByte() }.toByteArray()
}
fun ByteArray.toHex(): String = joinToString(separator = "") { eachByte -> "%02X".format(eachByte) }