如何将uint256变量转换为int256变量? [英] How do I convert a uint256 variable to an int256 one?

查看:10
本文介绍了如何将uint256变量转换为int256变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过在下面的return price;代码中键入return timeStamp;来打印uint timeStamp

pragma solidity ^0.6.7;

import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";

contract PriceConsumerV3 {

AggregatorV3Interface internal priceFeed;

/**
 * Network: Kovan
 * Aggregator: BTC/USD
 * Address: 0x6135b13325bfC4B00278B4abC5e20bbce2D6580e
 */
constructor() public {
    priceFeed = AggregatorV3Interface(0x6135b13325bfC4B00278B4abC5e20bbce2D6580e);
}

/**
 * Returns the latest price
 */
function getThePrice() public view returns (int) {
    (
        uint80 roundID, 
        int price,
        uint startedAt,
        uint timeStamp,
        uint80 answeredInRound
    ) = priceFeed.latestRoundData();
    return price;
    return timeStamp;
}
}

当我在Remix编译器上编译上面的代码时,它回答:

TypeError:返回参数类型uint256不能隐式转换为预期类型(第一个返回变量的类型)int256。返回时间戳;^-^

我倾向于认为我只需键入int256 return timeStamp或类似的内容,而不是return timeStamp;,但我想不出来。

感谢反馈。

推荐答案

可以使用以下语法将uint类型转换为int

return int(timeStamp);
注意:对于2^255-1(int最大值)和2^256-1(uint最大值)之间的值,这将溢出(在实度0.7.x和更早版本中)或引发异常(在实度0.8+)。但这很可能只是理论上的情况,因为时间戳不应该有这么大的值。


请注意,此行无法访问,因为您已在前一行上返回price

(
    uint80 roundID, 
    int price,
    uint startedAt,
    uint timeStamp,
    uint80 answeredInRound
) = priceFeed.latestRoundData();
return price; // the `price` is returned, and the function doesn't execute after this line
return timeStamp; // this is ignored because of the early return on previous line

如果要返回多个值,可以使用以下语法:

// note the multiple datatypes in the `returns` block
function getThePriceAndTimestamp() public view returns (int, uint) {
    (
        uint80 roundID, 
        int price,
        uint startedAt,
        uint timeStamp,
        uint80 answeredInRound
    ) = priceFeed.latestRoundData();
    return (price, timeStamp); // here returning multiple values
}

这篇关于如何将uint256变量转换为int256变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆