Jamil Ahmed
Jamil Ahmed

Reputation: 159

How do I convert u32 data to &str in an embedded platform?

I want to convert u32 integer data to string in embedded Rust, but the problem is in embedded we can't use std code, so is there any way to do this?

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);

Upvotes: 4

Views: 5849

Answers (1)

Jamil Ahmed
Jamil Ahmed

Reputation: 159

answer found

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}");
}

Upvotes: 5

Related Questions