Hex Format
Начиная с Kotlin: 2.2
inline fun HexFormat(builderAction: HexFormat.Builder.() -> Unit): HexFormat
Создаёт новый HexFormat, настраивая параметры форматирования с помощью указанного builderAction, и возвращает полученный формат.
Полученный формат можно передавать функциям форматирования и разбора, чтобы задать способ выполнения форматирования и разбора. Например, val format = HexFormat { number.prefix = "0x" } создаёт новый HexFormat и присваивает его переменной format. Когда этот format передаётся функции форматирования числа, полученная строка будет содержать "0x" в качестве префикса шестнадцатеричного представления форматируемого числового значения. Например, вызов 58.toHexString(format) приведёт к результату "0x0000003a".
Сведения о настройке параметров форматирования см. в разделе HexFormat.Builder, а информацию о том, как настроенные параметры форматирования влияют на результаты форматирования и разбора, — в разделе HexFormat.
Билдер, переданный в качестве получателя функции builderAction, действителен только во время её выполнения. Использование билдера за пределами этой функции может привести к неопределённому поведению.
Возвращает
Новый экземпляр HexFormat, настроенный указанным образом с помощью builderAction.
Параметры
Функция, настраивающая параметры форматирования получателя HexFormat.Builder.
Примеры
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
}
© 2010–2026 JetBrains s.r.o. and Kotlin Programming Language contributors
Licensed under the Apache License, Version 2.0.
https://kotlinlang.org/api/core/kotlin-stdlib/kotlin.text/-hex-format.html