Rust Function: Hex string to integer
Rust Result and Option types: Exercise-7 with Solution
Write a Rust function that converts a hexadecimal string to an integer and returns Option
Sample Solution:
Rust Code:
fn hex_string_to_int(hex_string: &str) -> Option<u64> {
// Attempt to parse the hexadecimal string into a u64 integer
match u64::from_str_radix(hex_string, 16) {
// If parsing succeeds, return the parsed integer wrapped in Some
Ok(parsed_int) => Some(parsed_int),
// If parsing fails (invalid input), return None
Err(_) => None,
}
}
fn main() {
// Test cases
let valid_hex_string = "BF3C"; // Valid hexadecimal string
let invalid_hex_string = "IJKL"; // Invalid hexadecimal string
// Test the hex_string_to_int function with a valid hexadecimal string
match hex_string_to_int(valid_hex_string) {
Some(parsed_int) => println!("Parsed integer: {}", parsed_int),
None => println!("Invalid hexadecimal input"),
}
// Test the hex_string_to_int function with an invalid hexadecimal string
match hex_string_to_int(invalid_hex_string) {
Some(parsed_int) => println!("Parsed integer: {}", parsed_int),
None => println!("Invalid hexadecimal input"),
}
}
Output:
Parsed integer: 48956 Invalid hexadecimal input
Explanation:
Here's a brief explanation of the above Rust code:
The function "hex_string_to_int()" takes a hexadecimal string 'hex_string' as input and attempts to parse it into a 'u64' integer using the "from_str_radix()" function. If parsing succeeds, the parsed integer is returned wrapped in 'Some'. If parsing fails (due to invalid input), 'None' is returned. The "main()" function provides test cases for both valid and invalid hexadecimal strings to demonstrate the behavior of the "hex_string_to_int()" function.
Rust Code Editor:
Previous: Rust Function: String length.
Next: Rust Function: Safe Division.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/error_handling/rust-result-and-option-types-exercise-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics