hexToInt method
Converts a hexadecimal string to an integer (int).
This method attempts to parse the string as a hexadecimal number. It performs several checks to ensure the input is a valid hexadecimal string and that the resulting value can be represented as an int (signed 64-bit).
The method correctly handles both uppercase and lowercase hex strings, normalizing to uppercase for the overflow comparison.
Returns:
An int representation of the hexadecimal string, or null if:
- The string is empty
- The string contains non-hexadecimal characters
- The value exceeds the maximum signed 64-bit integer (0x7FFFFFFFFFFFFFFF)
Prints a warning to the debug console if the input is invalid or too large.
Example:
'FF'.hexToInt(); // Returns 255
'ff'.hexToInt(); // Returns 255 (case-insensitive)
'1A3F'.hexToInt(); // Returns 6719
'7fffffffffffffff'.hexToInt(); // Returns 9223372036854775807 (max int64)
''.hexToInt(); // Returns null
'invalid-hex'.hexToInt(); // Returns null, prints a warning
'8000000000000000'.hexToInt(); // Returns null, prints a warning (too large)
Implementation
int? hexToInt() {
if (isEmpty) {
return null;
}
// Check if the hexadecimal string is valid using a regular expression.
if (!_hexRegex.hasMatch(this)) {
return null;
}
// Check if the hexadecimal string is too large to be represented as an int.
// Normalize to uppercase for consistent comparison since the input can be
// mixed case (e.g., '7fffffffffffffff' should equal '7FFFFFFFFFFFFFFF').
final String upperHex = toUpperCase();
if (length > 16 || (length == 16 && upperHex.compareTo(_maxInt64Hex) > 0)) {
return null;
}
// Convert the hexadecimal string to an int and return it.
return int.parse(this, radix: 16);
}