繁体   English   中英

如何将字符串转换为 bytes8?

[英]How to convert string to bytes8 in solidity?

我在function中得到了string参数,参数长度小于8,想把这个参数转成bytes8保存到数组中。 如何转换?

例如:

pragma solidity 0.8.0;
contract MyContract{
    bytes8 [] Names;
    
    function setName(string memory _name) public{
        Names.push(_name);
    }
}

此代码在solidity 0.8.7中有效

pragma solidity 0.8.7;
contract MyContract{
    bytes8 [] Names;
    
    function setName(string memory _name) public{
        // convert string to bytes first
        // then convert to bytes8
        bytes8 newName=bytes8(bytes(_name));
        Names.push(newName);
    }
}

或者在 solidity 中你可以传递 bytes8 作为参数

function setName(bytes8 _name) public{
        Names.push(_name);
    }

当您在前端调用它时,您将字符串转换为 bytes8,然后将其作为参数传递

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM