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

for example :

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


Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1