Cairo: Uint256

Cairo: Uint256

ยท

2 min read

Introduction

If you are confused about what value should be passed into the low and high of Uint256 in Cairo? you are not alone. I was confused the first time I saw it too. After digging into the code and asking around, I finally figured it out.

What is Cairo's Uint256?

Everything in Cairo is represented by felt. felt stands for Field Element, the only data type in Cairo. it is 251 bits unsigned integer.

Because a uint256 number has 256 bits in size, it can not be represented by a 251-bit felt. Therefore, it is necessary to split the uint256 number into two components: low and high. The low component represents the low 128 bits of the uint256 number, and the high component is the high 128 bits of the uint256 number. The binary value of low and high are padded with leading 0s up to the maximum resolution and put together side by side to form the uint256 number.

uint256.png

Uint256 is defined as a struct:

struct Uint256 {
    low: felt,

    high: felt,
}

Examples

For a better understanding, I have deployed a simple Cairo smart contract on testnet. The contract has only one view function get_uint256 that returns a Uint256 number in decimal from its low and high value.

@view
func get_uint256{syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr}(
    low: felt, high: felt
) -> (num: Uint256) {
    let num: Uint256 = Uint256(low, high);
    return (num,);
}

Let's say we want to have number 4 as an Uint256. To do so, we pass 4 to low and 0 to high:

let num: Uint256 = Uint256(low = 4, high = 0)

4 is 100 and 0 is 0 in binary. We add padding zeros to them and stack them side by side, like so:

uint256-4-0.png

Let's check it on our smart contract:

4-0.png

What about Uint256(low = 0, high = 4)? In the same token, we pad them with leading 0s to the maximum resolution and put them together:

That is 1361129467683753853853498429727072845824 in decimal. ๐Ÿ‘€

0-4.png

Conclusion

That's it for today. Thank you for reading this post, hopefully, it was useful. Let's keep on learning Cairo!

If you have any questions feel free to reach out to me on Twitter.

ย