Solidity – Complete Guide to Unsigned Integers in Solidity

solidity

Beginner dev, problem from ChainShot: Intro to Smart Contracts

Problem 2: Unsigned Integers

"Let's create three public state unsigned integers in our Contract: a, b, and sum.
Define the variable a as an uint8 with an initial value between 0 and 255.
If you declare the variable a as a uint8 you will actually be unable to store a value outside the range 0 to 255. If you try this directly in your program, you'll get a comrpile-time error!
Define the variable b as an uint16 with a value of at least 256. The range for a uint16 is 0 to 65535.
The variable sum should be a uint256 with the sum of the values stored in a and b.
It's perfectly valid to add a uint8 and a uint16 and store them in a uint256. Mix it up!
You can use uint256 or uint to declare the sum. The keyword uint is an alias for uint256 and it is often used!"

My answer so far, 2/3 validated. Need help on the the Sum part.

// SPDX-License-Identifier: MIT

pragma solidity ^0.8.4;

contract sum{

uint8 public a;

uint16 public b;

}

Best Answer

Maybe this is what they are requesting You to do:

contract sum {

uint8 public a;

uint16 public b;

uint256 public  sum = a + b;

}

Basically create a new state variable of type uint or uint256 (which are the same).

To learn more more about signed and unsigned integers, check this article: https://coinsbench.com/signed-vs-unsigned-integers-binary-representation-overflows-pitfalls-109bc1ef6ef0