hexToLong

Common
JVM
JS
Native
1.9
@ExperimentalStdlibApi fun String.hexToLong(
    format: HexFormat = HexFormat.Default
): Long

(source)

Parses a Long 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 16, the excess leading digits must be zeros. This ensures that the value represented by the hexadecimal digits fits into a 64-bit Long. 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".hexToLong()) // 58

// Parsing is case-insensitive
println("3A".hexToLong()) // 58

// Up to 16 hexadecimal digits can fit into a Long
println("ffffffffffffffff".hexToLong()) // -1

// Excess leading hexadecimal digits must be zeros
println("00ffffffffffffffff".hexToLong()) // -1
// "010000000000000000".hexToLong() // will fail with IllegalArgumentException

// Parsing an ULong results in the unsigned version of the same value
// In this case, (-1L).toULong() = ULong.MAX_VALUE
println("ffffffffffffffff".hexToULong()) // 18446744073709551615

// Using a custom format
val format = HexFormat { number.prefix = "0x" }
println("0x3A".hexToLong(format)) // 58

// Parsing fails if the input string does not conform to the specified format.
// In this case, the prefix is not present.
// "3A".hexToLong(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 a Long.

Return the Long value parsed from this string.