Solidity convert hex string to bytes

I try to convert hex string to bytes.

function MyContract() public {
string memory str = "A76A95918C39eE40d4a43CFAF19C35050E32E271";
array1 = bytes(str);

bytes memory  str1 = hex"A76A95918C39eE40d4a43CFAF19C35050E32E271";
array2 = str1;
}

In array1 I have only unicode from str like array1 - 41. In array 2 I have what I want array2 - a7. But I can't use hex with variable.

I want to use function arguments for conversion to bytes like:

function (string str) {
return bytes(hex(str))
}

Question: Is there any way to do the conversion in Solidity?

Thanks so much in advance.

This are very inefficient but should work

// Convert an hexadecimal character to their value
function fromHexChar(uint c) public pure returns (uint) {
if (byte(c) >= byte('0') && byte(c) <= byte('9')) {
return c - uint(byte('0'));
}
if (byte(c) >= byte('a') && byte(c) <= byte('f')) {
return 10 + c - uint(byte('a'));
}
if (byte(c) >= byte('A') && byte(c) <= byte('F')) {
return 10 + c - uint(byte('A'));
}
}

// Convert an hexadecimal string to raw bytes
function fromHex(string s) public pure returns (bytes) {
bytes memory ss = bytes(s);
require(ss.length%2 == 0); // length must be even
bytes memory r = new bytes(ss.length/2);
for (uint i=0; i<ss.length/2; ++i) {
r[i] = byte(fromHexChar(uint(ss[2*i])) * 16 +
fromHexChar(uint(ss[2*i+1])));
}
return r;
}

In any case I'd recommend to try to convert your hexadecimal data outside solidity.

• Thanks for the answer, the bottom is what I need, but it returns bytes. This may be a stupid question, but how do I get it as bytes32? – thefett Apr 27 '18 at 14:10
• @thefett It should be possible, declare bytes32 r instead of bytes memory r = new bytes(..). The problem is that it is not easy to modify indivual bytes of bytes32, but casting to uint and using shifts you can achieve that. – Ismael Apr 29 '18 at 6:47