Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to a string without allocating memory

I've been experiencing occasional lags in my Android game when the garbage collector runs. I ran DDMS and discovered that all of the memory being allocated by my application is from this line:

scoreString = String.valueOf(score);

What is the best way to convert an integer to a string without allocating any memory?

like image 945
Computerish Avatar asked Nov 22 '10 01:11

Computerish


People also ask

How do you convert int to string manually?

Using the to_string() Method This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.

How can a number be converted to a string?

The Integer.toString() method converts int to String. The toString() is the static method of Integer class. The signature of toString() method is given below: public static String toString(int i)

How do you convert int to string without using library functions in Python?

Using __str__() to convert an integer to string in python So, we can directly call the __str__() on the object. In our case we passed integer to str() function in previous example. Instead of it, we can directly call the __str__() function on int object to get a string representation of the integer i.e.


1 Answers

Allocate an array of characters to be displayed as the score, and use a lookup table of 0-9 (this conveniently maps to a 0-base array anyway) to append to this array based on each digit of the score.

Edit: To extract the digits from your score:

12345 mod 10 = 5
12345 mod 100 = 45 / 10 = 4.5 (floors to 4)
12345 mod 1000 = 345 / 100 = 3.45 (floors to 3)
12345 mod 10000 = 2345 / 1000 = 2.345 (floors to 2)
12345 mod 100000 = 12345 / 10000 = 1.2345 (floors to 1)

Also you'll know what the max length for the score character array should be based on whatever you're using to store score (i.e. int)

I recommend reverse-filling this array and initializing it to all '0' so your score will display like

0000000000
0000005127
like image 173
Doug Moscrop Avatar answered Sep 22 '22 03:09

Doug Moscrop