generated from transmissions11/foundry-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TypeConverts.sol
97 lines (89 loc) · 3.08 KB
/
TypeConverts.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.15;
contract TypeConverts {
// https://ethereum.stackexchange.com/questions/64998/converting-from-bytes-in-0-5-x?rq=1
function bytesToAddress(bytes memory _b) public pure returns (address) {
return address(tb20(_b));
}
function tb20(bytes memory _b) public pure returns (bytes20 _result) {
assembly {
_result := mload(add(_b, 0x20))
}
}
function uint2str(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
// // https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity
// function uint2str(uint256 _i)
// public
// pure
// returns (string memory _uintAsString)
// {
// if (_i == 0) {
// return "0";
// }
// uint256 j = _i;
// uint256 len;
// while (j != 0) {
// len++;
// j /= 10;
// }
// bytes memory bstr = new bytes(len);
// uint256 k = len;
// while (_i != 0) {
// k = k - 1;
// uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
// bytes1 b1 = bytes1(temp);
// bstr[k] = b1;
// _i /= 10;
// }
// return string(bstr);
// }
// https://stackoverflow.com/questions/68976364/solidity-converting-number-strings-to-numbers
function st2num(string memory numString) public pure returns (uint256) {
uint256 val = 0;
bytes memory stringBytes = bytes(numString);
for (uint256 i = 0; i < stringBytes.length; i++) {
uint256 exp = stringBytes.length - i;
bytes1 ival = stringBytes[i];
uint8 uval = uint8(ival);
uint256 jval = uval - uint256(0x30);
val += (uint256(jval) * (10 ** (exp - 1)));
}
return val;
}
// https://ethereum.stackexchange.com/questions/8346/convert-address-to-string/8447#8447
function addressToString(address x) internal pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint256 i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint256(uint160(x)) / (2 ** (8 * (19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2 * i] = char(hi);
s[2 * i + 1] = char(lo);
}
return string(abi.encodePacked("0x", s));
}
function char(bytes1 b) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
}