minLength

Specifies the minimum number of hexadecimal digits to be used in the representation of a numeric value, 1 by default.

The hexadecimal representation of a value is calculated by mapping each four-bit chunk of its binary representation to the corresponding hexadecimal digit, starting with the most significant bits.

When formatting:

  • If this option is less than the length of the hexadecimal representation:

  • If this option is greater than the length of the hexadecimal representation, the representation is padded with zeros at the start to reach the specified minLength.

  • If this option matches the length of the hexadecimal representation, the representation remains unchanged.

When parsing, this option is ignored. However, there must be at least one hexadecimal digit in the input string. If the number of hexadecimal digits exceeds the capacity of the type being parsed, based on its bit size, the excess leading digits must be zeros.

Since Kotlin

2.0

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   // By default, minLength is 1 and removeLeadingZeros is false.
println(0x3a.toHexString()) // 0000003a

// Specifying a minLength shorter than the hex representation with removeLeadingZeros set to false.
println(0x3a.toHexString(HexFormat { number.minLength = 4 })) // 0000003a

// Specifying a minLength shorter than the hex representation with removeLeadingZeros set to true.
val shorterLengthFormat = HexFormat {
    number.removeLeadingZeros = true
    number.minLength = 4
}
println(0x3a.toHexString(shorterLengthFormat)) // 003a
println(0xff80ed.toHexString(shorterLengthFormat)) // ff80ed

// Specifying a minLength longer than the hex representation.
// removeLeadingZeros is ignored in this case.
val longerLengthFormat = HexFormat {
    number.removeLeadingZeros = true
    number.minLength = 12
}
println(0x3a.toHexString(longerLengthFormat)) // 00000000003a

// When parsing, minLength is ignored.
println("3a".hexToInt(longerLengthFormat)) // 58

// The number of hex digits can be greater than what can fit into the type.
println("00000000003a".hexToInt()) // 58
println("0000ffffffff".hexToInt()) // -1
// But excess leading digits must be zeros.
// "000100000000".hexToInt() // will fail with IllegalArgumentException 
   //sampleEnd
}