Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

embedded

rust

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);
like image 771
Jamil Ahmed Avatar asked Oct 17 '25 14:10

Jamil Ahmed


1 Answers

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}");
}
like image 145
Jamil Ahmed Avatar answered Oct 22 '25 05:10

Jamil Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!