|
| 1 | +// Author: NithinU2802 |
| 2 | +// Hexadecimal to Octal Converter: Converts Hexadecimal to Octal |
| 3 | +// Wikipedia References: |
| 4 | +// 1. https://en.wikipedia.org/wiki/Hexadecimal |
| 5 | +// 2. https://en.wikipedia.org/wiki/Octal |
| 6 | + |
| 7 | +pub fn hexadecimal_to_octal(hex_str: &str) -> Result<String, &'static str> { |
| 8 | + let hex_str = hex_str.trim(); |
| 9 | + |
| 10 | + if hex_str.is_empty() { |
| 11 | + return Err("Empty string"); |
| 12 | + } |
| 13 | + |
| 14 | + // Validate hexadecimal string |
| 15 | + if !hex_str.chars().all(|c| c.is_ascii_hexdigit()) { |
| 16 | + return Err("Invalid hexadecimal string"); |
| 17 | + } |
| 18 | + |
| 19 | + // Convert hex to decimal first |
| 20 | + let decimal = u64::from_str_radix(hex_str, 16).map_err(|_| "Conversion error")?; |
| 21 | + |
| 22 | + // Then convert decimal to octal |
| 23 | + if decimal == 0 { |
| 24 | + return Ok("0".to_string()); |
| 25 | + } |
| 26 | + |
| 27 | + let mut num = decimal; |
| 28 | + let mut octal = String::new(); |
| 29 | + |
| 30 | + while num > 0 { |
| 31 | + let remainder = num % 8; |
| 32 | + octal.push_str(&remainder.to_string()); |
| 33 | + num /= 8; |
| 34 | + } |
| 35 | + |
| 36 | + // Reverse the string to get the correct octal representation |
| 37 | + Ok(octal.chars().rev().collect()) |
| 38 | +} |
| 39 | + |
| 40 | +#[cfg(test)] |
| 41 | +mod tests { |
| 42 | + use super::*; |
| 43 | + |
| 44 | + #[test] |
| 45 | + fn test_hexadecimal_to_octal() { |
| 46 | + assert_eq!(hexadecimal_to_octal("A"), Ok("12".to_string())); |
| 47 | + assert_eq!(hexadecimal_to_octal("FF"), Ok("377".to_string())); |
| 48 | + assert_eq!(hexadecimal_to_octal("64"), Ok("144".to_string())); |
| 49 | + assert_eq!(hexadecimal_to_octal("0"), Ok("0".to_string())); |
| 50 | + } |
| 51 | + |
| 52 | + #[test] |
| 53 | + fn test_invalid_input() { |
| 54 | + assert_eq!(hexadecimal_to_octal(""), Err("Empty string")); |
| 55 | + assert_eq!( |
| 56 | + hexadecimal_to_octal("GG"), |
| 57 | + Err("Invalid hexadecimal string") |
| 58 | + ); |
| 59 | + assert_eq!( |
| 60 | + hexadecimal_to_octal("XYZ"), |
| 61 | + Err("Invalid hexadecimal string") |
| 62 | + ); |
| 63 | + } |
| 64 | +} |
0 commit comments