如何在嵌入式平台上将u32数据转换为&str?

4

我想在嵌入式Rust中将u32整数数据转换为字符串,但问题在于在嵌入式系统中我们无法使用std代码库,那么有没有其他方法可以实现这个功能呢?

let mut dist = ((elapsed as f32 / mono_timer.frequency().0 as f32 * 1e6) / 2.0) / 29.1;
let dist = dist as u32;
let data = String::from("data:");
data.push_str(dist);

1个回答

5

找到答案了

use core::fmt::Write;
use heapless::String;

fn foo() {
    let dist = 100u32;
    let mut data = String::<32>::new(); // 32 byte string buffer
    
    // `write` for `heapless::String` returns an error if the buffer is full,
    // but because the buffer here is 32 bytes large, the u32 will fit with a 
    // lot of space left. You can shorten the buffer if needed to save space.
    let _ = write!(data, "data:{dist}");
}

当我尝试使用use heapless::consts::*;时,会返回一个编译错误,指出未找到consts。是否有更新的答案?因为这似乎是我需要的解决方案。 - tufelkinder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接