Bob*_*eng 4 blockchain solidity
在 Solidity 中,有没有办法将 int 转换为 string ?
例子:
pragma solidity ^0.4.4;
contract someContract {
uint i;
function test() pure returns (string) {
return "Here and Now is Happiness!";
}
function love() pure returns(string) {
i = i +1;
return "I love " + functionname(i) + " persons" ;
}
}
Run Code Online (Sandbox Code Playgroud)
什么是函数名?谢谢!
小智 95
solidity ^0.8.0
import "@openzeppelin/contracts/utils/Strings.sol";
Strings.toString(myUINT)
Run Code Online (Sandbox Code Playgroud)
对我有用。
小智 18
Solidity 0.8.0 更新:
https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol 中的uint2str()函数现在已经过时,将无法工作,但这里是更新的代码,使用solidity 0.8.0 :(在上一个版本中有一个溢出错误,但solidity <0.8.0 忽略了它,因为它不会影响答案,但现在会引发错误)
也被更改为和 +,-,* 等等将来自 SafeMath 库。bytebytes1
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint 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);
}
Run Code Online (Sandbox Code Playgroud)
Concrete_Buddhas 答案在 Solidity 0.8.0 中不起作用。这是修订版:
function uint2str(
uint256 _i
)
internal
pure
returns (string memory str)
{
if (_i == 0)
{
return "0";
}
uint256 j = _i;
uint256 length;
while (j != 0)
{
length++;
j /= 10;
}
bytes memory bstr = new bytes(length);
uint256 k = length;
j = _i;
while (j != 0)
{
bstr[--k] = bytes1(uint8(48 + j % 10));
j /= 10;
}
str = string(bstr);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
这里的两个帖子给出了回应:
https://ethereum.stackexchange.com/questions/10811/solidity-concatenate-uint-into-a-string
https://ethereum.stackexchange.com/questions/10932/how-to-convert-string-to-int
function uintToString(uint v) constant returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i + 1);
for (uint j = 0; j <= i; j++) {
s[j] = reversed[i - j];
}
str = string(s);
}
Run Code Online (Sandbox Code Playgroud)
问候
| 归档时间: |
|
| 查看次数: |
17770 次 |
| 最近记录: |