Reputation: 353
I found this code when I searched for ways to convert uint value into string. It's from OpenZeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/3dac7bbed7b4c0dbf504180c33e8ed8e350b93eb/contracts/utils/Strings.sol#L16-L36
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
I can't understand what bytes1(uint8(48 + uint256(value % 10)))
means, specifically what does the magic number 48
mean here. Appreciate it if someone can shed some light on it.
Upvotes: 1
Views: 333
Reputation: 181047
48 is the ascii value for the character '0'.
The loop in question basically takes the value modulo 10 (that is, the least significant digit) and adds 48 to it, converting it to an ascii character. It then divides the number by 10 to do the same with the second least significant digit and so on.
As an example, if value
is 437, the modulo leaves 7. That 7 is added to 48 to make 55 which is the ascii value for the character '7'. It then divides value
by 10 to do the same with the number 43 to get the next character.
Upvotes: 4