hexToUShort
Parses an UShort
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 four, the excess leading digits must be zeros. This ensures that the value represented by the
hexadecimal digits fits into a 16-bit UShort
.
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.
import kotlin.test.*
fun main(args: Array<String>) {
//sampleStart
// Using the default format
println("3a".hexToShort()) // 58
// Parsing is case-insensitive
println("3A".hexToShort()) // 58
// Up to 4 hexadecimal digits can fit into a Short
println("ffff".hexToShort()) // -1
// Excess leading hexadecimal digits must be zeros
println("00ffff".hexToShort()) // -1
// "010000".hexToShort() // will fail with IllegalArgumentException
// Parsing an UShort results in the unsigned version of the same value
// In this case, (-1).toUShort() = UShort.MAX_VALUE
println("ffff".hexToULong()) // 65535
// Using a custom format
val format = HexFormat { number.prefix = "0x" }
println("0x3A".hexToShort(format)) // 58
// Parsing fails if the input string does not conform to the specified format.
// In this case, the prefix is not present.
// "3A".hexToShort(format) // will fail with IllegalArgumentException
//sampleEnd
}
Parameters
format
- the HexFormat to use for parsing, HexFormat.Default by default.
Exceptions
IllegalArgumentException
- if this string does not conform to the specified format, or if the hexadecimal
digits represent a value that does not fit into an UShort
.
Return the UShort
value parsed from this string.