HexFormat

Builds a new HexFormat by configuring its format options using the specified builderAction, and returns the resulting format.

The resulting format can be passed to formatting and parsing functions to dictate how formatting and parsing should be conducted. For example, val format = HexFormat { number.prefix = "0x" } creates a new HexFormat and assigns it to the format variable. When this format is passed to a number formatting function, the resulting string will include "0x" as the prefix of the hexadecimal representation of the numeric value being formatted. For instance, calling 58.toHexString(format) will produce "0x0000003a".

Refer to HexFormat.Builder for details on configuring format options, and see HexFormat for information on how the configured format options affect formatting and parsing results.

The builder provided as a receiver to the builderAction is valid only within that function. Using it outside the function can produce an unspecified behavior.

Since Kotlin

1.9

Return

A new instance of HexFormat configured as specified by the builderAction.

Parameters

builderAction

The function that configures the format options of the HexFormat.Builder receiver.

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   // Specifying format options for numeric values.
println(58.toHexString(HexFormat { number.removeLeadingZeros = true })) // 3a
println("0x3a".hexToInt(HexFormat { number.prefix = "0x" })) // 58

// Specifying format options for byte arrays.
val macAddressFormat = HexFormat {
    upperCase = true
    bytes {
        bytesPerGroup = 2
        groupSeparator = "."
    }
}
val macAddressBytes = byteArrayOf(0x00, 0x1b, 0x63, 0x84.toByte(), 0x45, 0xe6.toByte())
println(macAddressBytes.toHexString(macAddressFormat)) // 001B.6384.45E6
println("\"001B.6384.45E6\".hexToByteArray(macAddressFormat).contentEquals(macAddressBytes) is ${"001B.6384.45E6".hexToByteArray(macAddressFormat).contentEquals(macAddressBytes)}") // true

// Creating a format that defines options for both byte arrays and numeric values.
val customHexFormat = HexFormat {
    upperCase = true
    number {
        removeLeadingZeros = true
        prefix = "0x"
    }
    bytes {
        bytesPerGroup = 2
        groupSeparator = "."
    }
}
// Formatting numeric values utilizes the `upperCase` and `number` options.
println(58.toHexString(customHexFormat)) // 0x3A
// Formatting byte arrays utilizes the `upperCase` and `bytes` options.
println(macAddressBytes.toHexString(customHexFormat)) // 001B.6384.45E6 
   //sampleEnd
}