Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert i32 to a string representing the ASCII character

Tags:

ascii

rust

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
}
like image 533
user1610406 Avatar asked Dec 04 '22 01:12

user1610406


1 Answers

First, you don't need to return a String, a &'static str is sufficient. Second, you could simply set up an array of &'static strs with all code representations you like, and use .get(_) to get the relevant string slices, as long as all your char codes are consecutive (which they should be if I have my ASCII right). Even if they aren't, you can always put empty strings in the gaps.

The code should look like the following:

const CHARS: [&'static str; 128] = ["NUL", "SOH", "STX", .., "DEL"];

fn get_char_code(c: i32) -> &'static str {
    CHARS.get(c as usize).unwrap_or("")
}
like image 65
llogiq Avatar answered Jun 03 '23 00:06

llogiq