Since the type returned is a string
, the numbers are stored in a dynamic bytes
array. This means that each character occupies a single byte
slot. The ASCII/UTF-8 bit representation of numbers is linearly increasing, you can parse the numbers as follows:
pragma solidity ^0.4.24;
contract NumParser {
string[] public numArray;
uint256[] public shouldBe;
constructor() public {
numArray.push("31");
numArray.push("25");
numArray.push("24");
shouldBe.push(31);
shouldBe.push(25);
shouldBe.push(24);
uint256[] memory result = parseNums(numArray);
for (uint256 i = 0; i < result.length; i++) {
assert(result[i] == shouldBe[i]);
}
}
function parseNums(string[] numsToParse) internal pure returns (uint256[]) {
uint256[] memory parsed = new uint256[](numsToParse.length);
for (uint256 i = 0; i < numsToParse.length; i++) {
bytes memory temp = bytes(numsToParse[i]);
for (uint256 j = 0; j < temp.length; j++) {
parsed[i] += (uint256(temp[j]) - 48) * (10**(temp.length - 1 - j));
}
}
return parsed;
}
}
The constructor
contains a verification test that the function does indeed work correctly. The function you want to use is the parseNums
function.
EDIT: You should change your original question to include that you are receiving the array in string
format.
I have altered my function to work with your array as follows:
pragma solidity ^0.4.24;
contract NumParser {
string public numArray;
uint256[] private tempContainer;
uint256[] public shouldBe;
constructor() public {
numArray = "[\"31\", \"25\", \"24\"]";
shouldBe.push(31);
shouldBe.push(25);
shouldBe.push(24);
uint256[] memory result = parseNums(numArray);
tempContainer.length = 0;
for (uint256 i = 0; i < result.length; i++) {
assert(result[i] == shouldBe[i]);
}
}
function parseNums(string numsToParse) internal returns (uint256[]) {
bytes memory converted = bytes(numsToParse);
for (uint256 i = 0; i < converted.length; i++) {
if (converted[i] == 34) {
tempContainer.push(0);
uint256 j = i + 1;
for (; converted[j] != 34; j++) {
tempContainer[tempContainer.length - 1] += (uint256(converted[j]) - 48);
tempContainer[tempContainer.length - 1] *= 10;
}
tempContainer[tempContainer.length - 1] /= 10;
i = j;
}
}
return tempContainer;
}
}
Keep in mind that processing a string
like this is quite costly. You also cannot use a memory
array compared to the first solution because memory
arrays need to have a pre-declared size while you cannot find the amount of numbers you are going to get in your array from the raw string.
This also increases the gas cost so I would advise zeroing the length as shown within the constructor
to reduce the cost.
uint8
array.