Skip to content

Instantly share code, notes, and snippets.

@FoxIvan
Created September 6, 2017 05:23
Show Gist options
  • Save FoxIvan/63e3c3fb79b110be044b25bd9bc1855e to your computer and use it in GitHub Desktop.
Save FoxIvan/63e3c3fb79b110be044b25bd9bc1855e to your computer and use it in GitHub Desktop.
bytes to hex
  private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
  
  public static String toHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int byteValue = bytes[i] & 0xFF;
            hexChars[i * 2] = HEX_ARRAY[byteValue >>> 4];
            hexChars[i * 2 + 1] = HEX_ARRAY[byteValue & 0x0F];
        }
        return new String(hexChars);
    }
@darkstone
Copy link

Here is kotlin version of the same for anyone ending here:

private const val hexChars = "0123456789abcdef"

fun ByteArray.toHex(): String {
    return fold(StringBuilder(size * 2)) { stringBuilder, byte ->
        stringBuilder.apply {
            val octet = byte.toInt()
            val i0 = (octet and 0xF0) ushr 4
            val i1 = (octet and 0x0F)
            append(hexChars[i0])
            append(hexChars[i1])
        }
    }.toString()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment