1

i'm doing a project in C++

the function hx_drv_uart_getchar() only receives 1 uint8_t dtype at a time. how can i convert all received characters from this function into a float array?

the string i am sending over here will be like "-1.2341, 0.9871, 4.5121~" where ~ is to let receiver know its the end of the string so the characters i am receiving will be something like '-' -> '1' ->'.' ->'2' ->'3' ->'4'-> '1'->','-> so on and so forth

how can i concatenate them and convert it into a float array: arr = {-1.2341, 0.9871, 4.5121}?

the code below is my implementation but acceldata is "45494650515249" after converting. i am suspecting its in ascii form.

so my question is how can i convert received uint8_t data to string and then convert the whole string to a float array? or are there any straightforwards ways? i've been stuck here for a few days already... please advise thank you :)

std::string acceldata;
uint8_t getchar = 0;
hx_drv_uart_getchar(&get_ch);
acceldata = get_ch;
while(get_ch != '~'){
    hx_drv_uart_getchar(&get_ch);
    acceldata += std::to_string(get_ch);
}
Ang Weijun
  • 11
  • 2
  • A "C++-ish" way could be creating your own `streambuf` implementation, and using it with `istream`, similarly to the `std::cin >> something;` for standard input. There is a [similar post](https://stackoverflow.com/questions/14086417/how-to-write-custom-input-stream-in-c) here on SO, but I would probably go with this particular example: https://en.cppreference.com/w/cpp/io/basic_streambuf/underflow - it shows exactly the one-character-at-a-time case what you have. – tevemadar Feb 26 '22 at 14:51
  • Personally I’d read in the entire string. Split on `,` then `stof` them – Taekahn Feb 26 '22 at 15:05
  • i don't get why you are talking about `characters` but with `uint8_t`. `uint8_t` sounds better like `byte`. So the question is : **Are you getting the numbers like values or like characters?** The overload of `std::to_string` that get a `uint8_t` as argument is trasforming its value in a character. I think your purpose was to get a character from the stream that `hx_drv_uart_getchar` is probably reading. So a good way of doing this is: `auto ch = static_cast(get_ch);`. In this way you can actually read the string till the `~` character is received (so you must check `ch` in the while) – IkarusDeveloper Feb 26 '22 at 16:30
  • Take a look to [this](https://onlinegdb.com/9pabHbSQF) minimal `solution` of your problem. (if my suspects about your stream reading are correct) – IkarusDeveloper Feb 26 '22 at 16:54

0 Answers0