Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdlib>
- #include <iostream>
- using namespace std;
- void intToString(int, char *);
- int countdigits(int);
- int main(int argc, char** argv)
- {
- char gewicht[12];
- intToString(0x0, gewicht);
- cout << gewicht << endl;
- intToString(0x80000000, gewicht);
- cout << gewicht << endl;
- intToString(0x7fffffff, gewicht);
- cout << gewicht << endl;
- intToString(0xffffffff, gewicht);
- cout << gewicht << endl;
- intToString(0xffffffff, gewicht);
- cout << gewicht << endl;
- return 0;
- }
- void intToString(int numb, char * gewicht)
- {
- int digits;
- int neg = 0;
- char digit_cache;
- //Zahl = 0, Sonderfall fuer den while schleife nicht funktioniert
- if (numb == 0)
- {
- gewicht[0] = '0';
- gewicht[1] = 0; //0 am Ende des Strings, da puts einen 0 terminierenden String erwartet
- return;
- }
- digits = countdigits(numb); //Anzahl Ziffern der Zahl
- char arr[digits + 1]; //Array erstellen und Laenge auf Anzahl der Digits + 1 setzen, fuer '0' am ende des Strings
- arr[digits] = 0; //eben diese '0' an die letze Stelle des Arrays schreiben
- if (numb < 0) {
- arr[0] = '-'; //Wenn Zahl negativ ist, '-' an position 0
- neg = 1;
- }
- while (numb != 0)
- {
- //Die hinterste Ziffer isolieren
- if (neg)
- digit_cache = (numb % 10) * -1; //Zahl negativ. BSP: -1234 mod 10 = -4 deshalb * -1
- else
- digit_cache = numb % 10;
- digits--;
- arr[digits] = digit_cache + '0';
- numb /= 10;
- }
- //entstandenen String in lokale Variable des aufrufenden Programms uebertragen
- int i = 0;
- for (i; i < 12; i++) {
- gewicht[i] = arr[i];
- }
- }
- int countdigits(int nr)
- {
- int count = 0;
- if (nr < 0) //Anzahl der Digits erhoeht sich durch '-' um 1
- count = 1;
- while (nr != 0) //Anzahl der Digits zaehlen
- {
- nr /= 10;
- count++;
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement