I am new to solidity programming and sorry if my question is very basic.
I am wondering if we can cast msg.value to uint248
Example below ; uint value; value = (uint248) (msg.value);
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityI am new to solidity programming and sorry if my question is very basic.
I am wondering if we can cast msg.value to uint248
Example below ; uint value; value = (uint248) (msg.value);
Here's a simple example to demonstrate casting msg.value
to a uint248
value using Browser Solidity with the following code:
pragma solidity ^0.4.8;
contract Test {
uint248 public value;
function Test() {
value = 123;
}
function () payable {
value = uint248(msg.value);
}
}
The screen below shows the deployment of the code to the JavaScript VM:
I've set the Value field to 456.789 and clicked on the (fallback) function, simulating the sending of 456.789 ETH to the contract:
I've set the Value field back to 0 and clicked on the value button to show that the msg.value
of 456.789 ETH was casted to a uint248
field:
For casting, use value = uint248(msg.value);
Casting to save 8 bits in this case is not worth it and will probably cost more gas due to unpacking: see Why does uint8 cost more gas than uint256?
Even when using a struct of uint248 and uint8, it is best to actually test whether you are getting some gas savings.
uint248
? Generally it is more efficient to leave it as auint256
– Tjaden Hess♦ Feb 17 '17 at 22:32