Users img
chinmay3
over 1 year ago  Karma: 53
What is the best practice to store a color in Solidity?

I have a struct where I want to store a color.

Is it better to store it as a string or as a uint32?
Which one will consume less gas? Do I need to considere something else?

struct Object {
string hexColor; // \"#407ac7\"
// or
uint32 rgbColor; // \"064122199\"
}
Solidity
DApp-design
gas
cost
color
Users img
chinmay3
over 1 year ago  Karma: 53
What is the best practice to store a color in Solidity?

I have a struct where I want to store a color.

Is it better to store it as a string or as a uint32?
Which one will consume less gas? Do I need to considere something else?

struct Object {
string hexColor; // \"#407ac7\"
// or
uint32 rgbColor; // \"064122199\"
}
Solidity
DApp-design
gas
cost
color

ONE ANSWER
eduardonunesp
over 1 year ago Karma: 817

You can use bytes4, which will store 3 bytes for RGB and one byte for Alpha channel (transparency). Like:

pragma solidity ^0.4.19;

contract Color {
    bytes4 public color;

    function setColor(bytes4 _color) public {
        color = _color;
    }
}

Also because isn't a dynamic type like string it tends to consume less gas, been more predictable about the cost.

setColor("0xFF000000");

For instance, setting opaque red color

You can use bytes4, which will store 3 bytes for RGB and one byte for Alpha channel (transparency). Like:

pragma solidity ^0.4.19;

contract Color {
    bytes4 public color;

    function setColor(bytes4 _color) public {
        color = _color;
    }
}

Also because isn't a dynamic type like string it tends to consume less gas, been more predictable about the cost.

setColor("0xFF000000");

For instance, setting opaque red color

Earn tokens by posting and answering questions about blockchain!
Karma to eth
YOUR ANSWER