1

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;

}

1 Answer 1

0

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

1
  • Awesome, that worked, it makes sense now. Thanks for the help and that link
    – zil00
    Sep 16, 2022 at 22:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.