hexToByte
Parses a Byte
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 two, the excess leading digits must be zeros. This ensures that the value represented by the hexadecimal digits fits into an 8-bit Byte
. 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 Byte
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 a Byte
.
Samples
import kotlin.test.*
fun main() {
//sampleStart
// Using the default format
println("3a".hexToByte()) // 58
// Parsing is case-insensitive
println("3A".hexToByte()) // 58
// Up to 2 hexadecimal digits can fit into a Byte
println("ff".hexToByte()) // -1
// Excess leading hexadecimal digits must be zeros
println("00ff".hexToByte()) // -1
// "0100".hexToByte() // will fail with IllegalArgumentException
// Parsing an UByte results in the unsigned version of the same value
// In this case, (-1).toUByte() = UByte.MAX_VALUE
println("ff".hexToULong()) // 255
// Using a custom format
val format = HexFormat { number.prefix = "0x" }
println("0x3A".hexToByte(format)) // 58
// Parsing fails if the input string does not conform to the specified format.
// In this case, the prefix is not present.
// "3A".hexToByte(format) // will fail with IllegalArgumentException
//sampleEnd
}