0

I'm aware that a conversion from uint256 to uint8 looks like this:

uint8(A_UINT256_NUMBER)

But how is a uint8 calculated from uint256?

There's definitely loss of data, but I assumed that converting to uint8 simply meant taking the first or last 8 bits of the uint256 number.

I did some console.log() in the .sol file using Hardhat, but it proved both assumptions wrong. When my uint256 was:

uint hashed = uint(keccak256(abi.encodePacked(blockhash(block.number - 1), block.timestamp))
console.log(hashed) // 88631825676121136580333262905198704734650330576553363943113505420509106239582

The uint8 conversion of the above returned:

uint8 answer = uint8(hashed);
console.log(answer) // 94

Unless I'm doing this wrong, there doesn't seem to be a connection between them.

1 Answer 1

0

Found the answer - it just needed a bit more digging.

uint8 takes the last 2 characters of a uint256 hexadecimal. In the example above:

88631825676121136580333262905198704734650330576553363943113505420509106239582 // decimal
= 0xC3F3D5E971FB24DF07463BC04B9518288E6E495556A1180BC517428AD8FD785E // hexadecimal

With the last 2 characters as 5E, it returns us 94 in decimal. Therefore,

uint8 answer = uint8(0xC3F3D5E971FB24DF07463BC04B9518288E6E495556A1180BC517428AD8FD785E) // 94

Would love to know why it is done this way though.

1
  • 1
    It's just the least significant (lowest order) 8 bits. In hex, each character represents 4 bits. Jun 1, 2021 at 10:35

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.