Skip to content

A multi-platform (JVM, Android) library of functions converting bytes and byte arrays to and from hex strings.

License

Notifications You must be signed in to change notification settings

ingonoka/HEXUTILS-LIB-MP

Repository files navigation

Hex Utils Library

1. Introduction

The hexutils library provides functions to convert byte arrays to strings of hex characters.

2. Usage

The library functions are provided as extension functions to ByteArray, Byte and String.

2.1. Converting a ByteArray to a printable hex 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

2.2. Convert a Byte into a printable hex String

(0x10).toHex() // 10
(0x10).toHex("0x") // 0x10

2.3. Convert a string of hex characters to a ByteArray

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.

About

A multi-platform (JVM, Android) library of functions converting bytes and byte arrays to and from hex strings.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages