remove Leading Zeros
Начиная с Kotlin: 2.2
val removeLeadingZeros: Boolean
Указывает, следует ли удалять ведущие нули в шестнадцатеричном представлении числового значения; по умолчанию — false.
Шестнадцатеричное представление значения вычисляется путем сопоставления каждого четырехбитного блока его двоичного представления соответствующей шестнадцатеричной цифре, начиная со старших битов.
При форматировании, если для этого параметра задано значение true и длина шестнадцатеричного представления превышает minLength, ведущие нули удаляются до тех пор, пока длина не станет равна minLength. Если длина не превышает minLength, этот параметр не влияет на результат форматирования.
При разборе этот параметр игнорируется.
Примеры
import kotlin.test.*
fun main() {
//sampleStart
// By default, removeLeadingZeroes is `false`
println(0x3a.toHexString()) // 0000003a
val removeLeadingZerosFormat = HexFormat { number.removeLeadingZeros = true }
// If there are no leading zeros, removeLeadingZeroes has no effect
println(0x3a.toByte().toHexString(removeLeadingZerosFormat)) // 3a
// The leading zeros in the hex representation are removed until minLength is reached.
// By default, minLength is 1.
println(0x3a.toHexString(removeLeadingZerosFormat)) // 3a
println(0.toHexString(removeLeadingZerosFormat)) // 0
// Here minLength is set to 6.
val shorterLengthFormat = HexFormat {
number.removeLeadingZeros = true
number.minLength = 6
}
println(0x3a.toHexString(shorterLengthFormat)) // 00003a
// When minLength is longer than the hex representation, the hex representation is padded with zeros.
// removeLeadingZeros is ignored in this case.
val longerLengthFormat = HexFormat {
number.removeLeadingZeros = true
number.minLength = 12
}
println(0x3a.toHexString(longerLengthFormat)) // 00000000003a
// When parsing, removeLeadingZeros is ignored
println("0000003a".hexToInt(removeLeadingZerosFormat)) // 58
//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/-number-hex-format/remove-leading-zeros.html