gollub

ItoA

May 7th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.24 KB | None | 0 0
  1. //u uart.h ide ovo
  2. void obrni(char *str, int length);
  3. unsigned char itoa(int num, char *str, int base);
  4.  
  5.  
  6.  
  7. //ovo ide u uart.c
  8.  
  9.  
  10. unsigned char itoa(int num, char *str, int base) {   // prebacije integer u karaktere(ASCII)
  11.  
  12.     int i = 0;
  13.     int ost;
  14.     bit negative = 0;
  15.  
  16.     if(num == 0) {
  17.         str[i++] = '0';
  18.         str[i] = '\0';
  19.         return str;
  20.     }
  21.  
  22.  // negativni brojevi za decimalni sistem, inace su brojevi unsigned
  23.     if (num < 0 && base == 10) {
  24.       negative = 1;
  25.         num = -num;
  26.     }
  27.  
  28.     while(num != 0) {
  29.         ost = num % base;
  30.             if (ost > 9) {
  31.                 str[i++] = (ost - 10) + 'a';
  32.             }
  33.             else {
  34.                 str[i++] = ost + '0';
  35.             }  
  36.          num = num/base;
  37.     }
  38.  
  39.     if (negative) {
  40.         str[i++] = '-';
  41.     }
  42.  
  43.     str[i] = '\0';  // terminiraj string
  44.  
  45.     // pozivam f-iju koja vraca ispravan redoslijed
  46.     obrni(str, i);
  47. }
  48.  
  49. // funkcija koja ce obrnuti redoslijed karaktera u stringu
  50. void obrni(char *str, int length) {
  51.  
  52.     int i = 0;
  53.     int j = length - 1;
  54.     char c;
  55.  
  56.     while(i < j) {
  57.         c = str[i];
  58.         str[i] = str[j];
  59.         str[j] = c;
  60.        
  61.         i++;
  62.         j--;  
  63.     }
  64. }
Add Comment
Please, Sign In to add comment