The hexutils
library provides functions to convert byte arrays to strings of hex characters.
The library functions are provided as extension functions to ByteArray
, Byte
and String
.
-
Convert [ByteArray] into string of hex characters. Each Byte is separated by ", " and prefixed with "0x"
byteArrayOf(1,2).toHex(brackets = true) // [ 0x01, 0x02 ] byteArrayOf(1,2).toHex(brackets = false) // 0x01 0x02
-
Convert [ByteArray] into string of hex characters. Each Byte is separated by " "
byteArrayOf(1,2).toHexShort() // 01 02
-
Convert [ByteArray] into string of hex characters. Bytes are not separated
byteArrayOf(1,2).toHexShortShort() // 0102
-
Convert a ByteArray into lines of [columns] bytes
val ba = byteArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 0x31 , 0x32, 0x33) ba.toHexChunked(printable = false) // 00 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 // 01 01 02 03 ba.toHexChunked(printable = true) // 00 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 ................ // 01 31 32 33 123 ba.toHexChunked(printable = true, lineNums = false) // 01 02 03 04 05 06 07 08 09 00 01 02 03 04 05 06 ................ // 31 32 33 123 ba.toHexChunked(printable = true, lineNums = true, columns = 10) // 01 02 03 04 05 06 07 08 09 00 .......... // 02 02 03 04 05 06 31 32 33 .....123
If remove
is set to true
then the following characters and character sequences will be removed before the string is converted: space,comma, square brackets and "0x"
"01 02 03 04".hexToBytes(removeSpace = true) // byteArrayOf(1, 2, 3 ,4)
"010203".hexToBytes() // byteArrayOf(1,2,3)
Removing spaces is done with regular expressions and is almost 30% slower and should be avoided
Copyright (c) 2024. Ingo Noka
This file belongs to project hexutils-mp. This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License. To view a copy of this license, visit https://creativecommons.org/licenses/by-nc-nd/4.0/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.