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\$
2
  • \$\begingroup\$ This is straight c. It would fit better in stack overflow. \$\endgroup\$ May 2, 2015 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\$ May 2, 2015 at 22:24

4 Answers 4

4
\$\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\$
3
  • \$\begingroup\$ snprintf version is better as it limits buffer usage. \$\endgroup\$
    – Ayhan
    May 2, 2015 at 22:07
  • \$\begingroup\$ Thanks! Will this work in mplab with xc8 compilrr? \$\endgroup\$ May 2, 2015 at 22:28
  • \$\begingroup\$ It should. This is ANSI-standard C. \$\endgroup\$
    – Adam Haun
    May 2, 2015 at 22:37
1
\$\begingroup\$

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

\$\endgroup\$
2
  • \$\begingroup\$ Thanks, but im not sure that this is supported by the xc8 compiler.. \$\endgroup\$ May 2, 2015 at 22:31
  • \$\begingroup\$ can you just try it out? \$\endgroup\$ May 2, 2015 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\$
0
\$\begingroup\$

ITOA bei XC8:

int main(void) {
  char Buffer[7];
  int i = 12345;
  itoa(Buffer, i, 10);
  UART_Write_Text_NL((uChr)Buffer); 
  return;
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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