4

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);
E_net4
  • 27,810
  • 13
  • 101
  • 139
Jamil Ahmed
  • 109
  • 1
  • 8
  • 1
    Does this answer your question? [How to format output to a byte array with no\_std and no allocator?](https://stackoverflow.com/questions/39488327/how-to-format-output-to-a-byte-array-with-no-std-and-no-allocator) – E_net4 Mar 12 '20 at 17:37

1 Answers1

5

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}");
}
Cruz Jean
  • 2,761
  • 12
  • 16
Jamil Ahmed
  • 109
  • 1
  • 8
  • When I try to use this, `use heapless::consts::*;` returns a compile error that consts is not found. Any update to this answer as it seems like just the solution I need. – tufelkinder Mar 27 '22 at 21:52