简体   繁体   English

如何将字符串转换为 bytes8?

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

I get string parameter in the function, and the length of the parameter is less than 8. and I want to convert this parameter to bytes8 for saving in the array.我在function中得到了string参数,参数长度小于8,想把这个参数转成bytes8保存到数组中。 How to convert it?如何转换?

for example:例如:

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

This code in solidity 0.8.7 works此代码在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);
    }
}

Or in solidity you could pass bytes8 as argument或者在 solidity 中你可以传递 bytes8 作为参数

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

when you call this in front end, you convert the string to bytes8 and then pass it as argument当您在前端调用它时,您将字符串转换为 bytes8,然后将其作为参数传递

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

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