2
\$\begingroup\$

EDIT: I am using this for programming a pic, so the C will be quite limited. The compiler is XC8.

Following function expects me to pass a string:

void OLED_string(char* str, short x, short y) {

    short pos = 0;
    char character = str[pos++];
    short startx = x;
    short starty = y;
    while(character != '\0') {
        OLED_char(character, startx, starty);
        if(startx >= 123) starty++; //wrap around
        startx += 5;
        character = str[pos++];
    }
}

I would like to display a value I have in a unsigned Integer. This value should be converted to Float and then divided by ten. Since float is very slow I would prefer to convert the integer to a string, and then simply add a point before the last character. I tried to pass directly the integer to this function but it does not work. Thanks!

\$\endgroup\$
  • \$\begingroup\$ This is straight c. It would fit better in stack overflow. \$\endgroup\$ – Scott Seidman May 2 '15 at 21:23
  • \$\begingroup\$ Well, its the code for a microcontroller programmed with mplab and xc8 compiler. People in this forum have a better specific knowledge as this c is quite limited if compared to the full C that the guys over there are used to.. \$\endgroup\$ – sharkyenergy May 2 '15 at 22:24
3
\$\begingroup\$

If you can use C standard library functions, sprintf() should handle the string conversion. Instead of adding the decimal point by shuffling characters around, you could use integer arithmetic:

char str[20];
unsigned int value = 105;

sprintf(str, "%u.%u", value / 10, value % 10);

Integer division won't be fast, but it should be faster than floating point. And I suspect that the int -> string conversion algorithm will be doing division anyway.

\$\endgroup\$
  • \$\begingroup\$ snprintf version is better as it limits buffer usage. \$\endgroup\$ – Ayhan May 2 '15 at 22:07
  • \$\begingroup\$ Thanks! Will this work in mplab with xc8 compilrr? \$\endgroup\$ – sharkyenergy May 2 '15 at 22:28
  • \$\begingroup\$ It should. This is ANSI-standard C. \$\endgroup\$ – Adam Haun May 2 '15 at 22:37
1
\$\begingroup\$

The itoa function is your friend. http://www.cplusplus.com/reference/cstdlib/itoa/

\$\endgroup\$
  • \$\begingroup\$ Thanks, but im not sure that this is supported by the xc8 compiler.. \$\endgroup\$ – sharkyenergy May 2 '15 at 22:31
  • \$\begingroup\$ can you just try it out? \$\endgroup\$ – Eugenio Pace May 2 '15 at 22:34
0
\$\begingroup\$

itoa and ftoa functions are both in stdlib.h in XC8 compiler so they will work on PIC. Just include <stdlib.h>

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.