João Abrantes
João Abrantes

Reputation: 4873

How to cast uint8 to int?

Doing int top = uint8(data[2]);

Gives: TypeError: Type uint8 is not implicitly convertible to expected type int256..

And doing int top = int(uint8(data[2]));

Gives: TypeError: Explicit type conversion not allowed from "uint8" to "int256".

I am using pragma ^0.8

Upvotes: 2

Views: 4716

Answers (1)

cameel
cameel

Reputation: 796

This conversion is ambiguous and depending on how you do it, you may get different results. This is why starting with version 0.8.0 the compiler forces you to explicitly tell it which one you meant.

For example if the value of data[2] is 255:

  • changing signedness first: 255 (uint8) -> -1 (int8) -> -1 (int)
  • changing width first: 255 (uint8) -> 255 (uint) -> 255 (int)

In the above I'm assuming that data is some kind of uint8 array - you did not specify that and if it's not, you may need extra conversions there. Depending on which conversion you want first, you need one of these:

int top = int(int8(data[2]));
int top = int(uint(data[2]));

Upvotes: 5

Related Questions