Converting to ASCII in C

前端 未结 9 1815
温柔的废话
温柔的废话 2021-01-05 07:26

Using a microcontroller (PIC18F4580), I need to collect data and send it to an SD card for later analysis. The data it collects will have values between 0 and 1023, or 0x0 a

9条回答
  •  既然无缘
    2021-01-05 08:05

    There's a way of doing it using subtractions, but I am not convinced it's faster than using subtractions and modulus on a "normal" CPU (may be different in an embedded environment).

    Something like this:

    char makedigit (int *number, int base)
    {
      static char map[] = "0123456789";
      int ix;
    
      for (ix=0; *number >= base; ix++) { *number -= base; }
    
      return map[ix];
    }
    
    
    char *makestring (int number)
    {
      static char tmp[5];
    
      tmp[0] = makedigit(&number, 1000);
      tmp[1] = makedigit(&number, 100);
      tmp[2] = makedigit(&number, 10);
      tmp[3] = makedigit(&number, 1);
      tmp[5] = '\0';
    
      return tmp;
    }
    

    Then, a call to makestring() should result in a (static, so copy it before overwriting) string with the converted number (zero-prefixed, at 4 characters width, as the original assumption is a value in the 0-1023 range).

提交回复
热议问题