hexToUInt
Parses an UInt
value from this string using the specified format.
The string must conform to the structure defined by the format. Note that only the HexFormat.number property of the format instance affects the parsing of a numeric value.
The input string must start with the prefix and end with the suffix defined in the HexFormat.number property. It must also contain at least one hexadecimal digit between them. If the number of hexadecimal digits exceeds eight, the excess leading digits must be zeros. This ensures that the value represented by the hexadecimal digits fits into a 32-bit UInt
. Parsing is performed in a case-insensitive manner, including for the hexadecimal digits, prefix, and suffix.
Refer to HexFormat.NumberHexFormat for details about the available format options and their impact on parsing.
Since Kotlin
1.9Return
the UInt
value parsed from this string.
Parameters
the HexFormat to use for parsing, HexFormat.Default by default.
Throws
if this string does not conform to the specified format, or if the hexadecimal digits represent a value that does not fit into an UInt
.
Samples
import kotlin.test.*
fun main() {
//sampleStart
// Using the default format
println("3a".hexToInt()) // 58
// Parsing is case-insensitive
println("3A".hexToInt()) // 58
// Up to 8 hexadecimal digits can fit into an Int
println("ffffffff".hexToInt()) // -1
// Excess leading hexadecimal digits must be zeros
println("00ffffffff".hexToInt()) // -1
// "0100000000".hexToInt() // will fail with IllegalArgumentException
// Parsing an UInt results in the unsigned version of the same value
// In this case, (-1).toUInt() = UInt.MAX_VALUE
println("ffffffff".hexToULong()) // 4294967295
// Using a custom format
val format = HexFormat { number.prefix = "0x" }
println("0x3A".hexToInt(format)) // 58
// Parsing fails if the input string does not conform to the specified format.
// In this case, the prefix is not present.
// "3A".hexToInt(format) // will fail with IllegalArgumentException
//sampleEnd
}