如何将 uint8 转换为 int?
How to cast uint8 to int?
正在做int top = uint8(data[2]);
给出:TypeError: Type uint8 is not implicitly convertible to expected type int256.
.
并且正在做 int top = int(uint8(data[2]));
给出:TypeError: Explicit type conversion not allowed from "uint8" to "int256".
我正在使用 pragma ^0.8
这种转换是不明确的,根据您的转换方式,您可能会得到不同的结果。这就是为什么从 0.8.0 版开始,编译器会强制您明确告诉它您的意思。
例如,如果 data[2]
的值为 255:
- 先改变符号: 255 (
uint8
) -> -1 (int8
) -> -1 (int
)
- 先改变宽度: 255 (
uint8
) -> 255 (uint
) -> 255 (int
)
在上面我假设 data
是某种 uint8
数组 - 你没有指定它,如果不是,你可能需要在那里进行额外的转换。根据您首先想要的转换,您需要以下之一:
int top = int(int8(data[2]));
int top = int(uint(data[2]));
正在做int top = uint8(data[2]);
给出:TypeError: Type uint8 is not implicitly convertible to expected type int256.
.
并且正在做 int top = int(uint8(data[2]));
给出:TypeError: Explicit type conversion not allowed from "uint8" to "int256".
我正在使用 pragma ^0.8
这种转换是不明确的,根据您的转换方式,您可能会得到不同的结果。这就是为什么从 0.8.0 版开始,编译器会强制您明确告诉它您的意思。
例如,如果 data[2]
的值为 255:
- 先改变符号: 255 (
uint8
) -> -1 (int8
) -> -1 (int
) - 先改变宽度: 255 (
uint8
) -> 255 (uint
) -> 255 (int
)
在上面我假设 data
是某种 uint8
数组 - 你没有指定它,如果不是,你可能需要在那里进行额外的转换。根据您首先想要的转换,您需要以下之一:
int top = int(int8(data[2]));
int top = int(uint(data[2]));