Solidity safesub防止溢出
在Solidity中两个无符号整型数字相减结果如果为负则会溢出,很严重的问题。所以在做数字运算时可以用DSSafeAddSub来保证运算的安全。
pragma solidity ^0.4.21; import "github.com/oraclize/ethereum-api/oraclizeAPI.sol"; contract DSSafeAddSub { function safeToAdd(uint a, uint b) pure internal returns (bool) { return (a + b >= a); } function safeAdd(uint a, uint b) pure internal returns (uint) { require(safeToAdd(a, b)); return (a + b); } function safeToSubtract(uint a, uint b) pure internal returns (bool) { return (b <= a); } function safeSub(uint a, uint b) pure internal returns (uint) { require(safeToSubtract(a, b)); return (a - b); } } contract Uint_vs_Uint8 is usingOraclize,DSSafeAddSub{ uint public uint_num; uint8 public uint8_num; string public str = "abc"; uint public result = uint_num - uint8_num; // 2 uint public uintVal = parseInt(str,2); // 0 uint public sub; uint public safesub; function setUint_num() public { uint_num = 10; } function setUint8_num() public { uint8_num = 2; } function subFun() public { sub = uint8_num - uint_num; //溢出 115792089237316195423570985008687907853269984665640564039457584007913129639928 } function safesubFun() public { safesub = safeSub(uint8_num, uint_num); // 0 } }
1.001^365=1.44......life is a project
原创文章,转载请注明出处!