簡體   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