Problem is 4 & 5 fit in less that 256 bits (each). You end up with tiny uints in the constant expression, and then those aren't easily converted to the uint256, so ... cast the type explicitly.
uint x = uint(4)/uint(5);
Takeaway is caution with constants because they may be cast in unexpected types.
A sketchy idea:
contract Divide {
function getDivided(uint numerator, uint denominator) public constant returns(uint quotient, uint remainder) {
quotient = numerator / denominator;
remainder = numerator - denominator * quotient;
}
}
Also check out "SafeMath" with "safeDiv()" at Zeppelin: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol
Also, since 4/5 obviously works out to 0 remainder 4, possibly you're really aiming for something more like 80%?
You can bump up the accuracy by working with "decimal" as is common in financial markets. You pass pairs around, the digits and the decimal offset.
So, 1.234 would be written as [1234, 3] with the 3 indicating that there is a decimal in the third spot.
In this case, you would calculate 80, with 2 decimal places (meaning .80).
4 * 10 ** 2 = 400, 400/5 = 80, we raised 4 by 10 ^ 2, so return ...
80,2 and optionally, a remainder.
Hope it helps.
The most optimized version:
function addressFrom(address _origin, uint _nonce) public pure returns (address) {
bytes memory data;
if (_nonce == 0x00) data = abi.encodePacked(byte(0xd6), byte(0x94), _origin, byte(0x80));
else if (_nonce <= 0x7f) data = abi.encodePacked(byte(0xd6), byte(0x94), _origin, byte(_nonce));
else if (_nonce <= 0xff) data = abi.encodePacked(byte(0xd7), byte(0x94), _origin, byte(0x81), uint8(_nonce));
else if (_nonce <= 0xffff) data = abi.encodePacked(byte(0xd8), byte(0x94), _origin, byte(0x82), uint16(_nonce));
else if (_nonce <= 0xffffff) data = abi.encodePacked(byte(0xd9), byte(0x94), _origin, byte(0x83), uint24(_nonce));
else data = abi.encodePacked(byte(0xda), byte(0x94), _origin, byte(0x84), uint32(_nonce));
return address(keccak256(data));
}
Update for Solidity 0.6.x:
function addressFrom(address _origin, uint _nonce) public pure returns (address) {
bytes memory data;
if (_nonce == 0x00) data = abi.encodePacked(byte(0xd6), byte(0x94), _origin, byte(0x80));
else if (_nonce <= 0x7f) data = abi.encodePacked(byte(0xd6), byte(0x94), _origin, uint8(_nonce));
else if (_nonce <= 0xff) data = abi.encodePacked(byte(0xd7), byte(0x94), _origin, byte(0x81), uint8(_nonce));
else if (_nonce <= 0xffff) data = abi.encodePacked(byte(0xd8), byte(0x94), _origin, byte(0x82), uint16(_nonce));
else if (_nonce <= 0xffffff) data = abi.encodePacked(byte(0xd9), byte(0x94), _origin, byte(0x83), uint24(_nonce));
else data = abi.encodePacked(byte(0xda), byte(0x94), _origin, byte(0x84), uint32(_nonce));
return address(uint256(keccak256(data)));
}
Best Answer
The Fixed Point Numbers documentation has a warning which says:
The warning at the bottom of Rational and Integer Literals says: