Home > OS >  How to convert string to bytes8 in solidity?
How to convert string to bytes8 in solidity?

Time:04-24

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. How to convert it?

for example :

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

CodePudding user response:

This code in solidity 0.8.7 works

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

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

  • Related