8

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);

q9f
  • 32,913
  • 47
  • 156
  • 395
Deepa
  • 241
  • 3
  • 5

3 Answers3

6

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.

eth
  • 85,679
  • 53
  • 285
  • 406
  • Is it bad practice to use uin248 for holding balance? I usually see balance stored with type uint. – Adam Soffer Jul 28 '17 at 22:00
  • @AdamSoffer Yes, unless you have another state variable that is uint8 and can use the unused 8 bits "next" to the uint248, there is no benefit to using uint248 for storing a balance. – eth Aug 10 '17 at 06:40
5

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:

enter image description here


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:

enter image description here


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:

enter image description here

BokkyPooBah
  • 40,274
  • 14
  • 123
  • 193
4

Try this: value = uint248(msg.value);

q9f
  • 32,913
  • 47
  • 156
  • 395
Victor Baranov
  • 2,027
  • 1
  • 17
  • 31