- Home /
I want some ints stored in a new int right after eachother
I have 9 ints that i want added together but instead of 1+2 = 3. I want them to stand next to eachother like this: 1, 2 = 12
Heres my code.
public int item1;
public int item2;
public int item3;
public int item4;
public int item5;
public int item6;
public int item7;
public int item8;
public int item9;
public GameObject[] slots;
private GetItemNumber getNum;
void OnMouseDown(){
print ("ss");
foreach (GameObject slot in slots) {
getNum = slot.GetComponent<GetItemNumber>();
getNum.SendNumbers();
}
Debug.Log (item1+""+item2+""+item3+""+item4+""+item5+""+item6+""+item7+""+item8+""+item9);
}
Answer by rutter · Sep 12, 2014 at 08:15 PM
There's an easy but risky way to do this: string operations.
int Concat(int x, int y) {
string s = x.ToString() + y.ToString();
return int.Parse(s);
}
That gets the job done in a hurry.
If you want more control or efficiency, it's worth considering how our number system works.
What is 12? It's 10 plus 2:
10 + 2
(1)(10^1) + (2)(10^0)
What is 654? It's 600 + 50 + 4:
600 + 50 + 4
(6)(10^2) + (5)(10^1) + (4)(10^0)
Each digit is worth ten times the digit after it.
If you have a series of single-digit numbers, you can count them up. Add each digit, multiplying by ten as you go:
int Concat(int[] digits) {
int total = 0;
for (int i=0; i<digits.length; i++) {
if (i > 0) total *= 10;
total += digits[i];
}
}
That assumes you have single-digit numbers. Though, you could use a similar process in reverse to break any multi-digit number into single-digit numbers.
Your answer
Follow this Question
Related Questions
Converting a string to an int 2 Answers
Best Way to Load 10^8 int Array in Unity/C#? 1 Answer
Monodevelop is expecting int from my float array 3 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers