Friday, 15 March 2013

embedded - Conversion of integer to char array in C -


I am developing an ARM embedded application. I stuck on a silly problem - I have an array of unsigned 8-bit integers:

  uint8_t days [42] = {0};  

This is initial with some data - Initial algorithm is very confusing and the irrelevant variable is introduced to the problem, so I will not return it here again. I look at this array in the debugger variable watch, and I'm pretty sure that it is filled with integer values ​​from 0 to 31.

I want to take any element of this array, say fifteen, and convert it to four * so that it can be displayed on my LCD screen . I write it again using the sprintf function:

  four d [3] = {'0', '0', '0'}; Springf (d, "% d", day [15]);  

Just a note: No, I can not use the stdlib itoa () function, because it does not conform to MISRA A standard, which I am obliged to follow

As a result, I get a binary zero value only in my d buffer any ideas?

For the MISRA-C compliance, you must be sure to sprintf () Or anything from stdio.h either you want to avoid any way to avoid sprintf like plague on any embedded system in general.

Writing a simple decimal integer for string conversion routine is quite basic things ... here is my attempt at an MISRA-C (2004 and 2012) Compatible Version: < Code> #include & lt; Stdint.h & gt; Zero dec_to_str (char * str, uint32_t val, size_t digits); Int main (empty) {Core Straw [3 U + 1U]; // assuming you want to end the redundant string? Dec_to_str (str, 31u, 3u); Return 0; } Zero dec_to_str (char * str, uint32_t val, size_t digits) {size_t i = 1u; {Str [num-i] = (four) ((well% 10u + 0 '); val == 10u;} [i-1u] = {0} for I & lt; = number; i ++) Assuming you want to end the redundant string?}

Note: uint32_t can be to swap out for a uint8_t, But then you need to add all kinds of places, to prevent indirect type propaganda, as required by MISRA, code will actually be ugly, such as:

  str [points- I] = (four) (uint8_t) ((uit8_t) (val% 10u) + '0');  < The only wise thing to do again / again is to divide that mistake into several lines: 

  uint8_t ch = (uit8_t) (val% 10u); Ch = (Uint8_t) (ch + '0'); Str [digits-I] = (four) f;  

No comments:

Post a Comment