How to convert i32 to a string representing the ASCII character

Viewed 4957

I'm re-doing a project in Rust this weekend and I need to convert an i32 to an ASCII character using it as the character code. All I have so far is a monstrous match that I'm hiding at the end of a file. Unfortunately, std::ascii does not support this conversion. Currently I'm just looking for a less ridiculous/more Rust-like(?) way to do this.

fn to_ascii(i: &i32) -> String {
    let a = match *i {
        0 => "NUL",
        1 => "SOH",
        2 => "STX",
        // ...
        125 => "}",
        126 => "~",
        127 => "DEL",
        _ => "",
    }
    a
}
5 Answers

You can cast as below:

println!("{}", 'A' as i8); // prints 65
println!("{}", 65 as char); // prints 'A'

Instead of i32, you can use u32 with from_u32:

use std::char::from_u32;

fn main() -> Result<(), u32> {
   let n = 0x21;
   let c = from_u32(n).ok_or(n)?;
   println!("{}", c);
   Ok(())
}
Related