Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <cstdlib>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. void intToString(int, char *);
  7. int countdigits(int);
  8.  
  9. int main(int argc, char** argv)
  10. {
  11.  
  12. char gewicht[12];
  13. intToString(0x0, gewicht);
  14. cout << gewicht << endl;
  15. intToString(0x80000000, gewicht);
  16. cout << gewicht << endl;
  17. intToString(0x7fffffff, gewicht);
  18. cout << gewicht << endl;
  19. intToString(0xffffffff, gewicht);
  20. cout << gewicht << endl;
  21. intToString(0xffffffff, gewicht);
  22. cout << gewicht << endl;
  23. return 0;
  24. }
  25.  
  26. void intToString(int numb, char * gewicht)
  27. {
  28. int digits;
  29. int neg = 0;
  30. char digit_cache;
  31.  
  32. //Zahl = 0, Sonderfall fuer den while schleife nicht funktioniert
  33. if (numb == 0)
  34. {
  35. gewicht[0] = '0';
  36. gewicht[1] = 0; //0 am Ende des Strings, da puts einen 0 terminierenden String erwartet
  37. return;
  38. }
  39.  
  40. digits = countdigits(numb); //Anzahl Ziffern der Zahl
  41.  
  42. char arr[digits + 1]; //Array erstellen und Laenge auf Anzahl der Digits + 1 setzen, fuer '0' am ende des Strings
  43. arr[digits] = 0; //eben diese '0' an die letze Stelle des Arrays schreiben
  44.  
  45. if (numb < 0) {
  46. arr[0] = '-'; //Wenn Zahl negativ ist, '-' an position 0
  47. neg = 1;
  48. }
  49.  
  50. while (numb != 0)
  51. {
  52. //Die hinterste Ziffer isolieren
  53. if (neg)
  54. digit_cache = (numb % 10) * -1; //Zahl negativ. BSP: -1234 mod 10 = -4 deshalb * -1
  55. else
  56. digit_cache = numb % 10;
  57.  
  58. digits--;
  59. arr[digits] = digit_cache + '0';
  60. numb /= 10;
  61. }
  62.  
  63. //entstandenen String in lokale Variable des aufrufenden Programms uebertragen
  64. int i = 0;
  65. for (i; i < 12; i++) {
  66. gewicht[i] = arr[i];
  67. }
  68. }
  69.  
  70. int countdigits(int nr)
  71. {
  72. int count = 0;
  73.  
  74. if (nr < 0) //Anzahl der Digits erhoeht sich durch '-' um 1
  75. count = 1;
  76.  
  77. while (nr != 0) //Anzahl der Digits zaehlen
  78. {
  79. nr /= 10;
  80. count++;
  81. }
  82.  
  83. return count;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement